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?
{...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
The previous answer was correct but just leaves the show property on the sub object, removing the other ones. To keep all properties and change the property you want you have to use:
{...state, [id] : {...state[id], show: !state[id].show}}
Have to add ...state[id]
this.setState(prevState => ({
...state,
state[id]: !prevState[id].show
}))
Here you have to take last state as prevState and then update the object with supplied key with opposite value of previous state's object.