1

I'm trying to destruct an object that can be null at a moment. For example with the following :

const { dolphin } = this.props.route.params;

I want dolphin to return null if route or params is null.

But whatever i try, i always got the exception "Cannot read property 'dolphin' of undefined.

Can anyone as a tip for this please ? Thanks

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Prozedsq
  • 67
  • 4

2 Answers2

2

Using nullish coalesce, optional chaining, and default value:

function test(x) {
  this.props = x;
  const { dolphin = null, whale = null } = this.props.route?.params ?? {};
  return { dolphin, whale };
}

console.log(test({
  route: {
    params: null
  }
}))

console.log(test({
  route: null
}))


console.log(test({
  route: { params: { dolphin: 1, whale: 2 } }
}))

Please make sure to note the compatibility table at the bottom for browsers. If you are using babel you should be okay. Since you are using React and Flow, you are probably already using browser targeted transpilation with Babel, so it shouldn't be an issue.

user120242
  • 14,918
  • 3
  • 38
  • 52
1

The closest you're going to get with a one-line destructuring assignment is this:

const { dolphin } = this.props.route?.params || { dolphin: null };

But it doesn't return null only if .route or .params is null; it does so if they are any falsy value.

GirkovArpa
  • 4,427
  • 4
  • 14
  • 43