Reputation: 1127
I'm trying to update a boolean attribute inside a state object, and I'm having some trouble. Here is what I'm attempting to do:
this.setState(
prevState => ({
selectedGrocery: {
...prevState.selectedGrocery,
checked: !prevState.checked
}
}),
() => {
console.log(this.state.selectedGrocery);
}
);
State selectedGrocery.checked
is initialized as false
, and when I call the above code, it changes to true
, but the next time the code is called, it doesn't change back to false
. Thanks in advance!
Upvotes: 1
Views: 489
Reputation: 112787
You need to use prevState.selectedGrocery.checked
in order to use the correct property.
this.setState(
prevState => ({
selectedGrocery: {
...prevState.selectedGrocery,
checked: !prevState.selectedGrocery.checked
}
}),
() => {
console.log(this.state.selectedGrocery);
}
);
Upvotes: 2