Search code examples
javascriptreactjsflowtypedestructuring

Javascript (React + Flow) - Destructuring with nullable nested objects


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


Solution

  • 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.