Skip to content
Advertisement

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

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement