22

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

0

6 Answers 6

39

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)
Sign up to request clarification or add additional context in comments.

1 Comment

The question is for null. That would give different results than undefined. if(myvalue.doesnotExist) would give an error null is not an object (evaluating 'myvalue.doesnotExist') in react. Actually the title is for null but the code is for undefined so you are correct with undefined. My apologizes.
5
  • 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>

2 Comments

suppose x is a object and has item . so first check whether x is undefined or null. then check x.items. check my answer .
sequence of operation matter ,in if statement first you have to check object then its properties.
2

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.

Comments

1

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 if(!x) or if(x==undefined)

Comments

1

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;

Comments

0

Simply you can use the condition

if (var){
// Statement
} else {
// Statement
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.