2

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>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100

2 Answers2

2

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?

rhoonah
  • 131
  • 6
1

You can use Math.max to cap the value.

const removeToCart = (productId) => {
    setCartItems((prev) => ({
      ...prev,
      [productId]: Math.max(prev[productId] - 1, 0),
    }));
};
Unmitigated
  • 76,500
  • 11
  • 62
  • 80