i've got stuck in react problems. I've create an online shop (front-end) website in react
const products = [
{ id: 1, name: "Oppo", price: 200, unit: 1, img: "oppo.jpg" },
{ id: 2, name: "Samsung", price: 250, unit: 1, img: "samsung.jpg" },
{ id: 3, name: "Vivo", price: 150, unit: 1, img: "vivo.jpg" },
];
/* const addToCart = (items) => {
setCartItem((cartItem) => [...cartItem, items])
console.log(cartItem)
}
function to add data in array to cartItem state
*/
const [cartItem, setCartItem] = usestate([]);
const addQuantity = (id) => {
const updateItem = cartItem.map((item) => {
if (item.id === id) {
return { ...item, unit: item.unit + 1, price: unit * item.price };
}
return item;
});
setCartItem(updateItem);
};
const reduceQuantity = (id) => {
const updateItem = cartItem.map((item) => {
const updateUnit = item.unit - 1;
if (item.id === id && item.unit > 1) {
return { ...item, unit: updateUnit, price: item.price / item.unit };
}
return item;
});
setCartItem(updateItem);
};
<div>
{cartItem.map((item) => {
return (
<div>
<button onClick={() => addQuantity(item.id)}>+</button>
<img src={item.IMG} alt="" />
<h3 className="name">{item.product}</h3>
<p className="price">{item.price}</p>
<p className="quantity">{quantity}</p>
<button onClick={() => reduceQuantity(item.id)}>-</button>
</div>
);
})}
</div>;
the initial unit of vivo is 1 and the price is 150
when I click addQuantity button, the unit has become 2, but because of the initial unit is 1, the price is still 150 (1 * 150). I add again, the unit is 3 and the price is 300 ( 2 * 150 ) where it should be 450.
how to keep the initial value not changes so the the function gives the correct result?
productsarray usinguseeStateto make it reactive