I'm trying to organize my state by using nested property like this:
this.state = {
someProperty: {
flag:true
}
}
But updating state like this,
this.setState({ someProperty.flag: false });
doesn't work. How can this be done correctly?
I found this to work for me, having a project form in my case where for example you have an id, and a name and I'd rather maintain state for a nested project.
Let me know!
There are many libraries to help with this. For example, using immutability-helper:
Or using lodash/fp:
Two other options not mentioned yet:
Disclaimer
the best answer of all - see example here
There is another shorter way to update whatever nested property.
On one line
Of course this is abusing some core principles, as the
state
should be read-only, but since you are immediately discarding the old state and replacing it with new state, it is completely ok.Warning
Even though the component containing the state will update and rerender properly (except this gotcha), the props will fail to propagate to children (see Spymaster's comment below). Only use this technique if you know what you are doing.
For example, you may pass a changed flat prop that is updated and passed easily.
Now even though reference for complexNestedProp did not change (shouldComponentUpdate)
the component will rerender whenever parent component updates, which is the case after calling
this.setState
orthis.forceUpdate
in the parent.