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?
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:
this.setState(prevState => {
let jasper = Object.assign({}, prevState.jasper); // creating copy of state variable jasper
jasper.name = 'someothername'; // update the name property, assign a new value
return { jasper }; // return new object jasper object
})
Instead of using Object.assign
we can also write it like this:
let jasper = { ...prevState.jasper };
2- Using spread operator