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 ?
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>
);
}
}
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With