I'm accessing an API with ReactJS. What is the best way to stop React Component crashing when it's accessing a property in the object provided by the API that may be 'undefined'?
An example of an error is:
TypeError: Cannot read property 'items' of undefined
To check for null in React, use a comparison to check if the value is equal or is not equal to null , e.g. if (myValue === null) {} or if (myValue !== null) {} . If the condition is met, the if block will run.
Yes you can, but instead of blank, simply return null if you don't want to render anything from component, like this: return (null); Another important point is, inside JSX if you are rendering element conditionally, then in case of condition=false , you can return any of these values false, null, undefined, true .
If you return null from a component, nothing is rendered. You can also return null to render nothing from a JSX expression.
To check if a variable is null or undefined in React, use the || (or) operator to check if either of the two conditions is met. When used with two boolean values the || operator returns true if either of the conditions evaluate to true .
if(typeof x !=='undefined' && typeof x.item !=='undefined'){
}
render(){
return(
<div>
(typeof x !=='undefined' && typeof x.item !=='undefined')?
<div>success</div>:
<div>fail</div>
</div>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
It looks like you're trying to access the property items
of a variable x
.
And if x
is undefined
, then calling x.items
will give you the error you mentioned.
Doing a simple:
if (x) {
// CODE here
}
or
if (x && x.items) { // ensures both x and x.items are not undefined
// CODE here
}
EDIT:
You can now use Optional Chaining, which looks sweet:
if (x?.items)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With