I have:
const { state: { mode } } = this
console.log(mode) //'mode'
console.log(state) //undefined
I want to declare the state
variable as well.
Is there a way to destructure this without breaking it into two statements?
const { state } = this
const { mode } = state
Default values in destructuring assignement only work if the variables either don't exist or their value is set to undefined . Any other value, including null , false and 0 , bypasses the default values in the destructuring statement. You can combine default values with renaming in the destructuring assignment.
To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.
Sure, just use a comma as if you were destructing another property of the parent object:
const obj = { state: { mode: 'str' }};
const { state: { mode }, state } = obj;
console.log(mode);
console.log(state);
Note that this looks very similar to, but is not the same as the following import
syntax you may have seen:
import React, { Component } from 'react'
Here, the variables in brackets are named exports, while the plain variable is the default export, which is entirely different from nested objects.
You can destructure the state
to a variable as well:
const { state, state: { mode } } = { state: { mode: 'mode' } };
console.log(mode) // 'mode'
console.log(state) // { mode: 'mode' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With