Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot read property of null doing destructing

Destructing is cool but I start to encounter serious issues when doing destructing of nested objects. I have this code:

const {
      credit: { amont },
    } = userProfile

This is dangerous because what if credit is null? the whole app breaks. How do I prevent this? I know one way is to use Typescript but I'd rather not. I start to doubt destructing for nested has no difference from using dot.

like image 612
Hoknimo Avatar asked Aug 28 '18 13:08

Hoknimo


People also ask

How do you handle Cannot Destructure property?

The "Cannot destructure property of undefined" error occurs when we try to destructure a property from a value that is equal to undefined . To solve the error provide a fallback when destructuring the property, e.g. const {name} = undefined || {}; .

Can we Destructure function in JavaScript?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.

How do you destruct an array of objects?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element. const [var1, var2, ...]


1 Answers

It isn't possible to solve this with deep destructuring. As another answer suggests, it's possible to use default values but they are applied only to undefined values:

const { credit: { amont } = {} } = userProfile || {};

While null values still result in error, it's necessary to do short-circuit evaluation for all objects that can potentially be nully:

const { credit } = userProfile || {};
const { amont } = credit || {};

This can be addressed with safe navigation utility function that reads the path and checks for nully values.

A renowned example is Lodash get:

const amont = _.get(userProfile, 'credit.amont');

I know one way is to use typescript but here I don't

It's possible to address this with TypeScript only if type safety is guaranteed. If userProfile comes from JSON response, runtime type checks have to be applied to assert that objects aren't null.

like image 162
Estus Flask Avatar answered Oct 06 '22 07:10

Estus Flask