I'm trying to destructure values directly in params fonction and affect default values with a general object (for each subProperties destructured) :
Example
const initialTest = {
name: 'myName',
surname: 'mySurname',
age: 100,
};
const MyComponent = ({
test: { name, surname, age } = initialTest,
}) => { ... }
<MyComponent test={{ name: 'myNameFromProps' }} />
My final desir is to have 3 const name, surname and age, with values from props (params of the function) if they are defined, and values from initialTest if not.
With this code, if test is not defined in props of component, it will use initialTest, but if test is defined with only name props like example above, I will get :
name = 'myNameFromProps'
surname undefined
age undefined
and I want :
name = 'myNameFromProps'
surname = 'mySurname'
age = 100
For sur I can do it with :
const MyComponent = ({
test: { name = initialTest.name, surname = initialTest.surname, age = initialTest.age },
}) => { ... }
But that's absolutly not funny...
I tried with parentheses test: ({ name, surname, age } = initialTest), but does not works and eslint is saying I'm a stupid dev... and he is right xD
If you have any suggestions / idea / solution, I would be happy to read it. Thx to all !
Unless you're actually using initialTest elsewhere, you can remove it and list the default values inside the destructuring of test:
const MyComponent = ({
test: { name: 'myName', surname: 'mySurname', age: 100 } = {},
}) => { ... }
Make sure to have the = {} at the end there, in case nothing exists in the test property.
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