0

What are the possible ways to handle this in Reactjs?

TypeError
Cannot read property 'something' of null
Aman Anku
  • 27
  • 7
  • The way to handle it, is not to do it. What do you expect to read from a null value? If, instead, you're trying to read from a *nullable* value (which is possibly null, not definitely null) - you use [optional chaining](https://stackoverflow.com/questions/32139078/null-safe-property-access-and-conditional-assignment-in-es6-2015) – Chase Mar 17 '21 at 07:35
  • https://stackoverflow.com/questions/6003884/how-do-i-check-for-null-values-in-javascript This may answer your question. – Prashant Mar 17 '21 at 07:35
  • https://stackoverflow.com/questions/44531204/best-way-to-handle-null-values-in-reactjs this me a bit – Aman Anku Mar 17 '21 at 07:45

1 Answers1

1

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.

pouria
  • 949
  • 8
  • 21
  • can I use this way to handle `blocks = blocks.something;` **if this gives something of null** `blocks = blocks && blocks.something;` – Aman Anku Mar 17 '21 at 07:41
  • @AmanAnku Yes that is also correct. But it's better to use another variable name for it: `const blockSomething = blocks && blocks.something`. But using optional chaining is the safest method. – pouria Mar 17 '21 at 08:06