How to update nested state properties in React
ecmascript-6, javascript, reactjs, setstate
Solution
In order to `setState` for a nested object you can follow the below approach as I think setState doesn't handle nested updates.
var someProperty = {...this.state.someProperty}
someProperty.flag = true;
this.setState({someProperty})
The idea is to create a dummy object perform operations on it and then replace the component's state with the updated object
Now, the spread operator creates only one level nested copy of the object. If your state is highly nested like:
this.state = {
someProperty: {
someOtherProperty: {
anotherProperty: {
flag: true
}
..
}
...
}
...
}
You could setState using spread operator at each level like
this.setState(prevState => ({
...prevState,
someProperty: {
...prevState.someProperty,
someOtherProperty: {
...prevState.someProperty.someOtherProperty,
anotherProperty: {
...prevState.someProperty.someOtherProperty.anotherProperty,
flag: false
}
}
}
}))
However the above syntax get every ugly as the state becomes more and more nested and hence I recommend you to use `immutability-helper` package to update the state.
See this answer on how to update state with `immutability-helper`.
Problem
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?
Related problems
- this.setState isn't merging states as I would expect
- Can you force a React component to rerender without calling setState?
- How to update single value inside specific array item in redux
- What is the most efficient way to deep clone an object in JavaScript?
- how to use Immutability helper to update a nested object within an array?