javascriptreactjstypescriptreplaceweb-developer-toolbar

What are the possible way to handle TypeError Cannot read property 'something' of null?


What are the possible ways to handle this in Reactjs?

TypeError
Cannot read property 'something' of null

Solution

  • You have two options:

    1- Always check for being null:

    let blah;
    
    if (obj) {
      blah = obj.something;
    }
    

    2- Use Optional Chaining

    const blah = obj?.something;
    

    From the docs:

    The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined.