Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setState of an object within an array

Given my state looks like so:

cart: [
  { id: 1, name: 'apple', price: 100, quantity: 1 }
]

How do I setState of that specific object's quantity property ?

like image 236
RogerFedFan Avatar asked Jan 02 '23 04:01

RogerFedFan


2 Answers

You can get the indexOf the item in the cart which you want to update, and update the cart with everything up to that item, your updated item, and the rest of the items.

Example

class App extends React.Component {
  state = {
    cart: [
      { id: 1, name: "apple", price: 100, quantity: 1 },
      { id: 2, name: "orange", price: 50, quantity: 10 },
      { id: 3, name: "banana", price: 20, quantity: 100 }
    ]
  };

  increaseQuantity = item => {
    this.setState(previousState => {
      const { cart } = previousState;
      const itemIndex = cart.indexOf(item);

      return {
        cart: [
          ...cart.slice(0, itemIndex),
          { ...cart[itemIndex], quantity: cart[itemIndex].quantity + 1 },
          ...cart.slice(itemIndex + 1)
        ]
      };
    });
  };

  render() {
    return (
      <div>
        {this.state.cart.map(item => (
          <div key={item.id} onClick={() => this.increaseQuantity(item)}>
            {item.name} {item.quantity}
          </div>
        ))}
      </div>
    );
  }
}
like image 199
Tholle Avatar answered Jan 04 '23 18:01

Tholle


You can update your cart as

updateCart(id, itemAttributes) {
  var index = this.state.cart.findIndex(x=> x.id === id);
  if (index === -1)
    // handle error
  else
    this.setState({
      cart: [
         ...this.state.cart.slice(0, index),
         Object.assign({}, this.state.cart[index], itemAttributes),
         ...this.state.cart.slice(index+1)
      ]
    });
}

then call your updateCart function with id of your cart item as

this.updateCart(1, {quantity: 2});
like image 40
Krishan Kumar Mourya Avatar answered Jan 04 '23 16:01

Krishan Kumar Mourya