2
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>
2
  • What does the props look like? Commented Apr 6, 2021 at 8:13
  • {user:{name:'myname'}} Commented Apr 6, 2021 at 8:18

3 Answers 3

4

Try this instead:

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

<div>{name}</div>
Sign up to request clarification or add additional context in comments.

5 Comments

the = '' is default value which is not needed, I don't mind got a undefined.
can the = {name: ''"} just be {}, imagine user have more than one property, I don't want to declare them one by one
No, you can simplify like user: { name } = {name: ''}. Because the default value always makes sure that it has value. Is that correct? @alice_morgan
can the = {name: ''"} just be {}, imagine user have more than one property, I don't want to declare them one by one @alice_morgan then you should stick to your original method
I mean the first default value is no need. the second is enough :)
2

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.

2 Comments

nope, you miss understood me, my question is if user object is empty then accessing name using destructing can get an error.
I've just updated my answer, pls take a look at it @alice_morgan
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.