Best way to handle null values in ReactJS?
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)
- In simple function you do it simply by if statement.
if(typeof x !=='undefined' && typeof x.item !=='undefined'){
}
- in JSX you do it in this way.
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>
This post talks about a few error handling strategy in your react app.
But in your case, I think using try-catch clause would be the most convenient.
let results;
const resultsFallback = { items: [] };
try {
// assign results to res
// res would be an object that you get from API call
results = res.items;
// do stuff with items here
res.items.map(e => {
// do some stuff with elements in items property
})
} catch(e) {
// something wrong when getting results, set
// results to a fallback object.
results = resultsFallback;
}
I assume that you are using this only for one particular pesky react component. If you want to handle similar type of error, I suggest you use ReactTryCatchBatchingStrategy
in the blog post above.