destructing nested object in react prop got error

Viewed 538
const {
    user: { name }
  } = props;

With the above code, I got

name of undefined when the user object is undefined

I like destructing but should it be used this way? The issue is there's no fallback to crash my react app. I rather do destruct and use ? as a fallback:

const {
    user
  } = props;

return <div>user?.name</div>
3 Answers

Try this instead:

const {
    user: { name = '' } = {name: ''}
  } = props;

<div>{name}</div>

In case that the property you are destructuring is not defined, You can assign "Default values" like this:

const props = {diffUser: {name: "Peter"}};
const { user: {name} = {name: "default-value"} } = props;
console.log(name);

The simpler example,

var { message: msg = "Something went wrong" } = {};
console.log(msg);

A variable can be assigned a default, in the case that the value unpacked from the object is undefined.

You can just add a quick default value an check for undefined or null string after:

const { user: { name } = {} } = props;

This way it will not throw an error if 'user' is undefined, name will just be undefined also.

Related