I created a card in reactJS for ecommerce app. Add to cart button and increment or decrement button also work here in same card. when I click increment button, they perform work accurately and increment number one by one. When I click decrement button, they could not perform task. I want, when I click decrement button, number decrements and stops on zero no negative value shown me.
const [cart, setCart] = useState({});
const handleDeleteToCart = (item) => {
if (cart.item > 0) {
setCart((pre) => ({ ...pre, [item.id]: (pre[item.id] || 0) - 1 }));
}
};
2
Answers
To ensure that the decrement button in your React component stops at zero and does not go into negative values, you need to add a condition to check if the value is greater than zero before decrementing it. You also need to handle the case where the item is not in the cart yet. Here’s how you can modify your handleDeleteToCart function to achieve this:
Try the below it will work