Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

stopping counter at 0

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Math.max to cap the value.

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading