Best way to handle undefined values in ReactJS?

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

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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


if (x && x.items) { // ensures both x and x.items are not undefined
  // CODE here


You can now use Optional Chaining, which looks sweet:

if (x?.items)

Solution 2

  • 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.
          (typeof x !=='undefined' && typeof x.item !=='undefined')?
<script src=""></script>
<script src=""></script>

Solution 3

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 => {
    // 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.

Solution 4

Best way to check for any such issue is to run your test code in google’s console.
Like for a null check, one can simply check

Solution 5

The optional chaining operator provides a way to simplify accessing values through connected objects when it’s possible that a reference or function may be undefined or null.

let customer = {
  name: "Carl",
  details: {
    age: 82,
    location: "Paradise Falls" // detailed address is unknown
let customerCity = customer.details?.address?.city;

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply