0

How can I update groceries item(set completed to True) in my toggleGroceryCompleteness method?

I tried this.setState({groceries[groceryIndex]:{completed:true});

   constructor(props) {
    super(props);
    this.state = {
      groceries: [
        {
          name: "Apples",
          completed: false
        }
      ],
      newGroceryName: ""
    };

  toggleGroceryCompleteness(groceryIndex) {
    console.log(groceryIndex);
    console.log(this.state.groceries[groceryIndex]);
  }

1 Answer 1

1

Since you're editing the value of a previously set state, you should use this definition of setState

this.setState((prevState, props) => {
    const newGroceries = prevState.groceries.slice()
    newGroceries[groceryIndex].completed = true

    return { ...prevState, groceries: newGroceries }
})

This takes the value of the groceries state array from before the setState call and assigns it to a new variable to be modified, accessing the given index and sets the completed property to true. Then returns a new object/state containing everything from the previous state value but a modified groceries property which is the new modified version.

Sign up to request clarification or add additional context in comments.

4 Comments

Two problems here: 1. newGroceries is a global variable—did you forget const =?; 2. This modifies the state directly. You probably meant to make a copies of the groceries array before modifying it: const newGroceries = prevState.groceries.slice();.
@JordanRunning yep! thanks for pointing that out! been writing too much python recently
@m_callens thanks! btw. why did you put props as argument in this arrow function?
@DemoDjango the props of the component is the second argument passed to this extended definition of setState. Whether you need it or not is up to you obviously but its there if you want it

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.