I’m creating a shopping cart app. When the user changes the quantity of an item, the price of the item should be updated along with it. However, in trying to implement this, I’ve encountered a bug where the items in the shopping cart are being duplicated rather than updated. Any help would be appreciated. Here is my code:
const [cart, setCart] = useState([]);
const handleQuantityChange = (e, product) => {
setCart((prevState) => [
...prevState,
...prevState.map((item) => {
if (item.id === product.id) {
return {
...item,
price: item.originalPrice * e.target.value,
quantity: e.target.value,
};
} else {
return item;
}
}),
]);
}
>Solution :
[...prevState, ...prevState.map()] is duplicating your list twice (one is the prevState, one is prevState.map())
You should modify your code like this
const [cart, setCart] = useState([]);
const handleQuantityChange = (e, product) => {
setCart((prevState) => [
...prevState.map((item) => {
if (item.id === product.id) {
return {
...item,
price: item.originalPrice * e.target.value,
quantity: e.target.value,
};
} else {
return item;
}
}),
]);
}
Another way without prevState but cart state
const [cart, setCart] = useState([]);
const handleQuantityChange = (e, product) => {
const updatedCart = cart.map((item) => {
if (item.id === product.id) {
return {
...item,
price: item.originalPrice * e.target.value,
quantity: e.target.value,
};
} else {
return item;
}
});
setCart(updatedCart);
}