I have a component where I have a state with some properties. The constructor looks like this:
constructor (props, context) {
super(props, context)
this.state = {
property1: '',
property2: '',
property3: '',
}
}
Say I want to update property1
, what I would usually do, is something like this:
this.setState({property1: 'my new property1'})
This however, is not working, the value of property1
will not change. For me to update any of the states, I have to do the following:
let obj = this.state
obj.property1 = 'my new property1'
this.setState(obj)
I know for a fact that the previous way used to work without a problem. Has something changed? Are there certain circumstances which I can't simply set each state property?
setState works asynchronously. If you call setState and then immediately check the value, it will not have updated yet.
this.setState({property1: 'my new property1'});
console.log(this.state.property1); //old value
if you want to wait for the new value, you can use the callback parameter in setState
this.setState({property1: 'my new property1'}, () => {
console.log(this.state.property1);
});
The reason why you see the state updating when you use the whole object is because you are mutating the state by editing it, which is bad.