Is it at all possible to update object's properties with setState
?
Something like:
this.state = {
jasper: { name: 'jasper', age: 28 },
}
I have tried:
this.setState({jasper.name: 'someOtherName'});
and this:
this.setState({jasper: {name: 'someothername'}})
The first results in a syntax error and the second just does nothing. Any ideas?
Best Answer
There are multiple ways of doing this, since state update is a async operation, so to update the state object, we need to use updater function with
setState
.1- Simplest one:
First create a copy of
jasper
then do the changes in that:Instead of using
Object.assign
we can also write it like this:2- Using spread syntax:
Note:
Object.assign
andSpread Operator
creates only shallow copy, so if you have defined nested object or array of objects, you need a different approach.Updating nested state object:
Assume you have defined state as:
To update extraCheese of pizza object:
Updating array of objects:
Lets assume you have a todo app, and you are managing the data in this form:
To update the status of any todo object, run a map on the array and check for some unique value of each object, in case of
condition=true
, return the new object with updated value, else same object.Suggestion: If object doesn't have a unique value, then use array index.