Undefined error getting in javascript (React Native) - javascript

I am storing particular key value in Database. But, While fetching the key value, getting undefined error.
await DbHandler.fetch(codeStatus)
.then((result) => {
const codeEnabledObj = result[0];
console.log('codeEnabledObj', codeEnabledObj);
let codeEnabled = false;
if (codeEnabledObj && codeEnabledObj.length > 0) { // this code not executing at all.
codeEnabled = codeEnabledObj[0].isEnabled;
}
console.log('codeEnabled', codeEnabled); // getting false always
console.log('codeEnabledObj.length[0]', codeEnabledObj.length); // undefined
})
.catch((error) => {
});
The issue is, It's not going inside if condition and throwing error like undefined.
But, If we print the response from db fetch
'codeEnabledObj', { type: 'codeStatus', isEnabled: true } // This is my response
Any suggestions?

Objects don't have length property like an array.
codeEnabledObj.length is wrong
use this,
Object.keys(codeEnabledObj).length
EDIT :
codeEnabledObj[0].isEnabled should be only codeEnabledObj.isEnabled

There is no property length in the codeEnabledObj , Moreover its not an Array.. so modifying the condition would work, where isEmpty could be a function used from
node package as underscore
if (isEmpty(codeEnabledObj)) { // ... }
and
codeEnabledObj.isEnabled
Thanks.

Related

Javascript - Array/Object exists in console.log, but returns undefined when accessing properties

I spent an unreal amount of time trying to figure out what the issue is.
I'm creating a chrome plugin accessing certain data on a LinkedIn page, and syncing this towards a CRM/ATS.
If my code is a bit messy with unnecessary uses of async or promises, I apologize, but it's cause I've tried several solutions at this point.
My variable quickbaseData logs without issue, and returns me a list of objects.
My variable linkedinData however, I am completely stuck with.
I want to be able to read from a list of objects or object.data, either doesn't matter. I've tried both at this point.
The problem is, regardless if i use an array or an object, as soon as I try to access a variable, I get undefined. The object exists, but I can't access it's length or it's property.
As you can see in the example below, when simply logging the object, It's able to read the data, however as soon as I try object.data or object?.data, it returns undefined or falsy values, despite the console log just having shown that the object exists with properties.
When I copy over the object to an instance of node in a terminal, I am able to access the properties of the object, however in my code below, as soon as I try to access a property it results in undefined
Any advice on what could be going on?
function findLinkedinCandidateInQuickbase(linkedinData, quickbaseData) {
console.log("Linkedin Data", linkedinData, linkedinData.data, Object.entries(linkedinData))
// Logs the following:
// linkedinData - {data: {full_name: 'Lorem Ipsum', email: 'N/A', phone: 'N/A', linkedin: '<url>'}
// linkedinData.data - undefined. I've tried both with optional chaining and without.
// Object.entries(linkedinData) - Array with length 0
const length = quickbaseData.length
const full_name = linkedinData?.full_name
const email = linkedinData?.email
const linkedin1 = linkedinData?.linkedin1
const linkedin2 = linkedinData?.linkedin2
const phone = linkedinData?.phone
Promise.all([full_name, email, linkedin1, linkedin2, phone]).then(value => console.log("promise value", value)) // promise value (5) [undefined, undefined, undefined, undefined, undefined]
console.log("rcvd: ", email, full_name, linkedin1, linkedin2, phone) // rcvd: undefined undefined undefined undefined undefined
for (let i = 0; i < length; i++) {
// console.log(quickbaseData[i])
let check = []
if (quickbaseData[i].candidate_name === full_name) check.append(true);
if (quickbaseData[i].email === email) check.append(true);
if (quickbaseData[i].linkedin === linkedin1) check.append(true);
if (quickbaseData[i].linkedin === linkedin2) check.append(true);
if (quickbaseData[i].phone === phone) check.append(true);
if (check.includes(true)) {
return quickbaseData[i].record_id
}
}
return null;
}
async function linkedinFindCandidate () {
let quickbaseData = await quickbaseCandidateData()
let linkedinData = await linkedinCandidateData()
Promise.all([linkedinData, quickbaseData]).then((res) => {
console.log(res) // I receive an array containing two objects, both objects (linkedinData and quickbaseData) are populated with the correct properties, no issues here.
let record_id = findLinkedinCandidateInQuickbase(res[0],res[1])
if (record_id) {
console.log("Candidate found: ", record_id)
} else {
console.log("I checked for a candidate but found none.")
}
})
}
export { linkedinFindCandidate };
EDIT:
Attempted the following, no luck:
console.log("Linkedin Data", linkedinData) // has data shows up as expected
console.log("Linkedin Data", linkedinData?.data) // undefined
console.log("Linkedin Data", linkedinData.data) // undefined
console.log("Linkedin Data", linkedinData["data"]) // undefined
console.log("Linkedin Data", JSON.stringify(linkedinData)) // empty object
console.log("Linkedin Data", Object.keys(linkedinData)) // empty array
console.log("Linkedin Data", Object.entries(linkedinData)) // empty array
I figured out the issue.
The problem was indeed occurring in linkedinCandidateData()
Here's a snippet of the code I had:
function linkedinCandidateData() {
let candidateData = {}
var intervalId = window.setInterval(async function () {
let grabbedData = await getCandidateData(candidateData, intervalId)
candidateData["data"] = grabbedData
}, 1000);
console.log('linkedin_fetch_candidate_data: ', candidateData)
return candidateData
}
This would immediately return {} as it's not waiting for the setInterval to do anything, and as such no data exists when I called the function.
The console shows a "live" version of objects, not always the data at the time of the console.log(). Eventually the object is mutated, so eventually there is data in it, but not by the time findLinkedinCandidateInQuickbase() is called.
I was previously planning on re-writing this using MutationObservers, and solved it in the process.
I eventually re-wrote it to this:
async function linkedinCandidateData() {
await waitForElm(".contact-info");
let candidateData = await getCandidateData();
console.log("Candidate data", candidateData);
return await Promise.resolve(candidateData); // this might be redundant, but it works at least.
}
and waitForElm (copied from elsewhere on Stackoverflow)
function waitForElm(selector) {
return new Promise((resolve) => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
const observer = new MutationObserver((mutations) => {
if (document.querySelector(selector)) {
resolve(document.querySelector(selector));
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
});
}

How to crawling using Node.js

I can't believe that I'm asking an obvious question, but I still get the wrong in console log.
Console shows crawl like "[]" in the site, but I've checked at least 10 times for typos. Anyways, here's the javascript code.
I want to crawl in the site.
This is the kangnam.js file :
const axios = require('axios');
const cheerio = require('cheerio');
const log = console.log;
const getHTML = async () => {
try {
return await axios.get('https://web.kangnam.ac.kr', {
headers: {
Accept: 'text/html'
}
});
} catch (error) {
console.log(error);
}
};
getHTML()
.then(html => {
let ulList = [];
const $ = cheerio.load(html.data);
const $allNotices = $("ul.tab_listl div.list_txt");
$allNotices.each(function(idx, element) {
ulList[idx] = {
title : $(this).find("list_txt title").text(),
url : $(this).find("list_txt a").attr('href')
};
});
const data = ulList.filter(n => n.title);
return data;
}). then(res => log(res));
I've checked and revised at least 10 times
Yet, Js still throws this result :
root#goorm:/workspace/web_platform_test/myapp/kangnamCrawling(master)# node kangnam.js
[]
Mate, I think the issue is you're parsing it incorrectly.
$allNotices.each(function(idx, element) {
ulList[idx] = {
title : $(this).find("list_txt title").text(),
url : $(this).find("list_txt a").attr('href')
};
});
The data that you're trying to parse for is located within the first index of the $(this) array, which is really just storing a DOM Node. As to why the DOM stores Nodes this way, it's most likely due to efficiency and effectiveness. But all the data that you're looking for is contained within this Node object. However, the find() is superficial and only checks the indexes of an array for the conditions you supplied, which is a string search. The $(this) array only contains a Node, not a string, so when you you call .find() for a string, it will always return undefined.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
You need to first access the initial index and do property accessors on the Node. You also don't need to use $(this) since you're already given the same exact data with the element parameter. It's also more efficient to just use element since you've already been given the data you need to work with.
$allNotices.each(function(idx, element) {
ulList[idx] = {
title : element.children[0].attribs.title,
url : element.children[0].attribs.href
};
});
This should now populate your data array correctly. You should always analyze the data structures you're parsing for since that's the only way you can correctly parse them.
Anyways, I hope I solved your problem!

how can I fix Cannot read property 'error' of undefined

I fetch Data and want to output the data. It Works but I also want to make a error handling.
Like:
const func = async data => {
try {
const res = await fetch('MY_URL);
const out = await res.json();
if(out) {
const name = out.result.name;
if(out.result.error) {
console.log('ERROR');
}
}
} catch(e) {
console.log(e);
}
};
Why I get this message?
Cannot read property 'error' of undefined
Ok, I dont have an object with error, but I want to say If there is an error object, then I want to show anything else.
How I fix it?
EDIT:
// Error Handling Statuscode
if (out.result[0].statuscode.error) {
allCircle[0].innerHTML = errorIcon;
domainInfo[0].innerText = out.result[0].statuscode.error;
}
I dont have statuscode.error. But If an Error in my system happens, then I get the property error. So how can I say If error exists? Because error property doesnt always exists.
You could try something like:
if(out.result && out.result.error) {
console.log('ERROR');
}
That way you would shortcut the evaluation of the error property if there is no result property in the first place.
Why I get this message?
Cannot read property 'error' of undefined
this because your out object does not have result parameter every time, and returns undefined at that time so you cant access to out.result.error because out.result is undefined
Solution
if(out?.result?.error) {
console.log('ERROR');
}

Cannot read property 'includes' of undefined in reactjs?

I try to resolve includes undefined, For that, I am using && operator.
isAllChecked = label => {
const { permission } = this.state;
false value - I need false value when I get data from API,
But I got an error that includes undefined. for that, I used && operator
but I got a true value, I don't need to get true value
const data = !groupItems.some(
x => !permission && !permission[label] && !permission[label].includes(x)
);
// console.log(true) //true
const data = !groupItems.some(
x => !permission[label].includes(x)
);
// I got a false value using static data without using && operator
// data output: false (accepted output- getting using static data, but I need
to get the same value when I get data from API, I got an error includes undefined without using && operator)
return data;
};
However, If I got data from API, this method is displayed can not read property undefined and when I am going to resolve 'includes' of undefined, I used && operator and I got true value.
Cannot read property 'includes' of undefined.
I don't need true value, I need false value for the initially mounted component.
my question is that how can I resolve Cannot read property 'includes' of undefined by using && operator or anything.
Here is my code sandbox: https://codesandbox.io/s/stackoverflow-a-60764570-3982562-v1-um18k
Instead of some, you can use every to check all.
isAllChecked = label => {
const { permission } = this.state;
const data = groupItems.every(
x => permission && permission[label] && permission[label].includes(x)
);
return data;
};

Cannot set property 'employeeNum' of undefined

I am writing a function that is meant to add an employee to the end of a list of employees, but I continue to be met with the error in the title. I've tried to alter the code, but I'm not sure what I'm doing wrong. Here's the function:
data-service.js
module.exports.addEmployee = function(employeeData) {
employeeData.employeeNum = ++empCount;
return new Promise(function(resolve,reject) {
employees.push(employeeData);
if(employees.length == 0) {
reject("no results returned");
}
resolve(employeeData);
});
}
server.js
app.get("/employees/add", (req,res) => {
res.render("addEmployee");
});
app.post("/employees/add", (req, res) => {
console.log(req.body);
res.redirect("/employees");
});
The current function is not the root of the problem... However, you are trying to set a property on a param that you expect to be an object. But the caller has either passed a variable that has a value === undefined, or perhaps is passing no params at all ( either way, the param employeeData is undefined and you have no checks against it, thus we see the error).

Categories