1

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!

1
  • Did my answer work for you? Consider accepting it if that's the case. Commented Nov 26, 2018 at 23:10

1 Answer 1

2

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);
  }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.