Pyot
Pyot

Reputation: 399

TypeError: Cannot read property 'foo' of null - Object, React

I'm getting TypeError: Cannot read property 'foo' of null when bar sometimes returns null.

How to prevent it when the value bar is null?

I thought bar: { foo } = {} it is solution but is not :(

export default function Component({ data }) {
  
  const {
    bar: { foo } = {},
  } = data

return (...)
}

Upvotes: 2

Views: 93

Answers (1)

Drew Reese
Drew Reese

Reputation: 202638

null is technically a defined value, so using a fallback value syntax fails here.

An easy solution is to use Optional Chaining operator combined with Nullish Coalescing.

const { foo } = data?.bar ?? {};

If data.bar is not null or undefined it is used, otherwise a fallback empty object is provided.

const data1 = { bar: { foo: 'foobar' }};
const data2 = { bar: null };

const { foo: foo1 } = data1?.bar ?? {};
console.log(foo1); // foobar

const { foo: foo2 } = data2?.bar ?? {};
console.log(foo2); // undefined

Upvotes: 3

Related Questions