Cannot read property 'includes' of undefined in reactjs? - javascript

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;
};

Related

Getting back multiple null values before getting back data in fetch request

how do I deal with getting back null in fetch requests? Eventually the request goes through but for some reason it gives back bunch of nulls before getting the data. could this be something wrong with my code or is this just normal fetch behavior?
Fetch setup
const [subDomains, setSubDomains] = useState(null)
const [website, setwebsite] = useState("twitter.com")
useEffect(() => {
async function fetchData() {
const response = await fetch("api_url="+website,{
headers: {
"X-Api-Key": "hidden"
}
})
const data = await response.json()
const subdomains = data["ContributingSubdomain"]
const convertedsubdomains = Object.keys(subdomains)
let otherdomains = []
for(let i=0; i < convertedsubdomains.length; i++) {
const subdomains2 = data.ContributingSubdomain[i]["DataUrl"]
otherdomains.push(subdomains2)
}
setSubDomains(otherdomains)
}
fetchData()
}, [website])
Then the subDomains prop is passed on to a component as domains
const SubDomains = ({domains}) => {
return (
<div>
<div>
{domains.forEach((e) =>
<h2>{e}</h2>
)}
</div>
</div>
)
}
export default SubDomains
I get an error saying TypeError: Cannot read properties of null (reading 'forEach')
When I console.log(domains), I see that I get a bunch of nulls before getting the actual data, which I assume is causing the above error. but I don't know what I'm doing wrong when requesting the data and passing it on
I really don't know why it returns keeps returning null before getting back the response, but since you initialized subDomains to null it'll return null for the very first render. But to fix the
TypeError: Cannot read properties of null (reading 'forEach')
all you have to do is check if domains has a value before mapping the values.
You can change this line:
{domains.forEach((e) =>
<h2>{e}</h2>
)}
to:
{domains?.forEach((e) =>
<h2>{e}</h2>
)}
Notice I added a question mark before domains. It's the optional chaining operator (?.). It enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
Also, why not map the values, rather than forEach. Like so:
{domains?.map((domain, index) =>
<h2 key={index}>{domain}</h2>
)}
If there are IDs that come along with the domains, then you can use those as the key instead of the index.

I am looking for a way to check if it gets response correctly in Fetch in JS

I am looking for a way to check if it gets response correctly in Fetch in JS
I made the code below.
however, this error happens:
test?id=96&date=2021-08-13:282
Uncaught (in promise) TypeError: responceData.forEach is not a function
at
let huu = fetch(url);
tmp_char = "";
huu.then(response => response.json()).then(
responceData =>{
responceData.forEach(element => {
if(element['date'] != null ){
//CHECK
}
})
}
)
Response
$a = Record::updateOrInsert(
['company_id' => (int) $request->id, 'date' => $request->date],
['numa' => (int) $request->numa ,'created_at' => now()]
);
Log::debug($a);
return response()->json($request, '200', ['Content-Type' => 'application/json','Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE);
I would like to check if the updateOrInsert does its transaction.
Logs Laravel
Argument 1 passed to Facade\Ignition\LogRecorder\LogMessage::__construct() must be of the type string or null, object given, called in /Users/Developments/www/vendor/facade/ignition/src/LogRecorder/LogMessage.php on line 34 {"userId":1,"exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): Argument 1 passed to Facade\Ignition\LogRecorder\LogMessage::__construct() must be of the type string or null, object given, called in /Users//Developments/www//vendor/facade/ignition/src/LogRecorder/LogMessage.php on line 34 at /Users/Developments/www/vendor/facade/ignition/src/LogRecorder/LogMessage.php:21)
I think responceData is an Object, but forEach only works for Arrays, you could try and bypass this with
for(let [key, value, ...] of Object.entries(reponceData)){
// Do something
}
or return your data as an array

Undefined error getting in javascript (React Native)

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.

Firebase Storage check if value is null in JavaScript

I want delete image only when storageId is not null.
I checked for null like so and value is null but it's fired so exception says not found that image.
How can I check if it's null?
const data = snapshot.data();
const ref = firebase.storage().ref();
if (data.storageId != null) {
ref.child('images').child(`${data.storageId}.jpg`).delete();
}
null is falsey so
if (data.storageId) {
ref.child('images').child(`${data.storageId}.jpg`).delete();
}
This will also cater for storageId is undefined.

React native cannot read property '0' of undefine

I'm new with ReactJS and today I have encountered a few problems.
I am currently using Redux to store my data and I was able to retrieve all the data from the props.
Ie.
const { recipe, loadingRDetail } = this.props;
console.log(recipe.macros);
recipe macros will show me 5 values in array.
Array Image Console Log
But when I tried to accessed to the array, It will throw me an error "Cannot read property '0' of undefined".
I have tried
console.log(recipe.macros[0])
and
const {macros} = recipe;
macros.map((i) => {
....
}...
I have no luck with both of these
This is the error I get
Red Warning error
Actually, it's just because your macros data is asynchronously loaded so you have to add a test to check if it's loaded.
You can try this:
const {macros} = recipe;
if (macros && macros.length) {
macros.map((i) => {
....
}...
}
Or if you already are in your Render method you can just try this :
const {macros} = recipe;
return (
{
macros && macros.length && /* It will check if macros has elements inside */
macros.map((i) => {
....
}...
}
}
)

Categories