I working on adding/removing items to a shopping cart in my react js project after I add items to the cart I add "-" and "+" buttons that on click should decrease/increase item quantity. I've managed to make the add-to-cart, increase work but I can't figure out how to delete the item from the cart when the quantity becomes 0. This is my code so far:
const [items, setItems] = useState([]);
const handleDecrease = (id) => {
setItems((prevState) =>
prevState.map(
(item) =>
item.id === id
? item.qty !== 1
? { ...item, qty: item.qty - 1 }
: item.id !== id
: item // !id
)
);
};
{items?.map((item) => {
return (
<div
key={item.id}
>
<div onClick={() => handleDecrease(item.id)}>-</div>
<div>{item.title}</div>
<div> ${item.price * item.qty}</div>
<div>{item.qty}</div>
</div>
);
})}
In my handleDecrease function, I check if the item quantity is !==1, then I decrease the quantity by 1; if the quantity is 1 and "-" is clicked again, I want to remove the item entirely from the items array, but my code only adds false
to the items array. How can I remove the item?
There are multiple ways to solve this problem, but the simplest is using the helping array:
const handleDecrease = (id) => {
const newItems = [];
items.map((item) => {
if (item.id === id) {
item.qty !== 1 && newItems.push({ ...item, qty: item.qty - 1 });
} else {
newItems.push(item);
}
});
setItems(newItems);
};