Miles Henrichs
Miles Henrichs

Reputation: 2410

How to update object at specific index in array within React state?

I'm building a calorie counting application using React. One of my components has in its state a list of food items:

this.state = {
   items: [
      {
        name: 'Chicken',
        selectedServing: {
           label: 'breast, grilled',
           quantity: 3
        }
      },
      {
        name: 'French Fries',
        selectedServing: {
           label: 'medium container',
           quantity: 1
        }
      }
   ]

When a user changes the serving size they consumed, I have to update the properties of the item in the items[] array. For example, if a user ate another chicken breast, I'd need to change the selectedServing object in items[0].

Since this array is part of the component's state, I'm using immutability-helper. I've found that I can properly clone and mutate the state in this way:

let newState = update(this.state, {
  items: {
    0: {
      selectedServing: {
        servingSize: {$set: newServingSize}
      }
    }
  }
});

The above code sets the servingSize for the first element in the items[] array, which is Chicken. However, I won't know the index of the object I need to update beforehand, so the 0 I hardcoded won't work. It seems that I can't store this index in a variable, because update() will think it's an object key.

How can I programmatically update an object at a specific index in a list?

Upvotes: 1

Views: 2116

Answers (1)

set0gut1
set0gut1

Reputation: 1672

An variable can be used as a key of an object.

let foo = 3
let newState = { items: { [foo]: { somthing: 'newValue' } } }
// above is equal to { items: { '3': { somthing: 'newValue' } } }

You can find the index number of 'Chicken' and save it into an variable, and use it to composit newState.

Upvotes: 2

Related Questions