0
static getDerivedStateFromProps(props) {
    const {
      name
    } = props.users;
    return { name };
  }
}

With the above code, I got an error of

TypeError
Cannot read property 'name' of undefined

What is the issue? I thought object deconstructing will handle automatically if users is undefined?

Can I use if statement in getDerivedStateFromProps and without return anything?

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
alice_morgan
  • 151
  • 7
  • 2
    `props.users` seems to be undefined. Destructuring doesn’t handle that. Consider using `props?.users`? – evolutionxbox Apr 06 '21 at 09:42
  • `"Destructuring doesn’t handle that"` --> You can still use destructuring with a default value like my[answer below](https://stackoverflow.com/a/66979479/9071943) @evolutionxbox – Nguyễn Văn Phong Apr 07 '21 at 04:18

1 Answers1

4

"I thought object deconstructing will handle automatically if users is undefined?"

No, it doesn't do automatically.

In the case of props.users seems to be undefined, you will get this error

const props = {};
const { user: {name} } = props;
console.log(name); 
// "Uncaught TypeError: Cannot read property 'name' of undefined",

Solution: Use Default value to get rid of that error

const props = {};
const { user: {name} = {name: "default-user-name"} } = props;
console.log(name);
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56