I have a state that looks like this:
state: {
1: {show: false, description: 'one'},
2: {show: false, description: 'two'},
3: {show: true, description: 'three'}
}
Depending on a variable "id" that comes from the action, I have to update the state.
Something like this:
var returnedState = {...state, [id].show : ![id].show}
How can I do this?
Using the spread operator to overwrite an object property It's a super clean syntax and easy to see which value we are overwriting. The only thing you must remember while using this method is that the order matters. If we, for instance, put the property we want to overwrite.
When you have nested data in an array or object the spread operator will create a deep copy of the top most data and a shallow copy of the nested data. lets take a look at what this means. this changes the reference at d[2] to a new array created with the spread operator!
Spread properties is a part of ECMAScript 2018 which is not supported by IE.
You can also mix in other properties with the object spread operator. Order matters: the object spread operator will overwrite properties that are defined before it, but not after.
{...state,
[id]: {
show: !state[id].show
}
}
that will copy the original state and then toggle the show value for the specific key/id that came from the action.
Here is a working code pen http://codepen.io/finalfreq/pen/mRBjZV
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