How to Update an Object's value in Array in React
In today's lesson, we will see how to update an object's value in array in React, let's assume that we are working on a shopping cart with React js, the user adds items to the cart, and the items are stored in an array, once he moves to view the cart he wants to update the quantity of a specific product, so how we can do that?
Update product quantity
So let's assume that the user wants to increment the quantity of the product in the cart you can do it like below:
incrementQ(item){
let productItem = cartItems.find(product => product.id === item.id);
if(productItem){
productItem.quantity += 1;
// you can update more fields
// productItem.size = item.size;
// productItem.color = item.color;
toast.success("Your product has been updated !", {
position: toast.POSITION.TOP_RIGHT
});
}
}