stopping counter at 0

49 views Asked by At

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

There are 2 answers

0
Unmitigated On BEST ANSWER

You can use Math.max to cap the value.

const removeToCart = (productId) => {
    setCartItems((prev) => ({
      ...prev,
      [productId]: Math.max(prev[productId] - 1, 0),
    }));
};
0
rhoonah On

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?