awebdev
awebdev

Reputation: 1127

Changing boolean attribute within a React state object

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

Answers (1)

Tholle
Tholle

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

Related Questions