231412 412389421
231412 412389421

Reputation: 313

Update array object by specific index

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]);
  }

Upvotes: 0

Views: 116

Answers (1)

m_callens
m_callens

Reputation: 6360

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.

Upvotes: 1

Related Questions