I have two functions that increment and decrement number of items by 1, but when I decrement I want to stop at 0? this are the functions
const addToCart = (productId) => {
setCartItems((prev) => ({
...prev,
[productId]: prev[productId] + 1,
}));
};
const removeToCart = (productId) => {
setCartItems((prev) => ({
...prev,
[productId]: prev[productId] - 1,
}));
};
they are then called in button by onClick action
<button
className="add-btn mx-2"
onClick={() => {
addToCart(product.id);
}}
>
{" "}
+
</button>
<button
className="add-btn mx-2"
onClick={() => {
removeToCart(product.id);
}}
>
{" "}
-
</button>
2
Answers
You can use
Math.max
to cap the value.Why not just modify removeToCart to look at the value of prev[productId] and if it is less than or equal to 0, then do nothing otherwise do the decrement?