skip to Main Content

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


  1. You can use Math.max to cap the value.

    const removeToCart = (productId) => {
        setCartItems((prev) => ({
          ...prev,
          [productId]: Math.max(prev[productId] - 1, 0),
        }));
    };
    
    Login or Signup to reply.
  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?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search