alice_morgan
alice_morgan

Reputation: 171

destructing nested object in react prop got error

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>

Upvotes: 2

Views: 972

Answers (3)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14208

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.

Upvotes: 2

Lek
Lek

Reputation: 137

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.

Upvotes: 0

glinda93
glinda93

Reputation: 8459

Try this instead:

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

<div>{name}</div>

Upvotes: 4

Related Questions