skip to Main Content

I created a card in reactJS for ecommerce app. Add to cart button and increment or decrement button also work here in same card. when I click increment button, they perform work accurately and increment number one by one. When I click decrement button, they could not perform task. I want, when I click decrement button, number decrements and stops on zero no negative value shown me.

const [cart, setCart] = useState({});
const handleDeleteToCart = (item) => {
    if (cart.item > 0) {
      setCart((pre) => ({ ...pre, [item.id]: (pre[item.id] || 0) - 1 }));
    }
  };

2

Answers


  1. To ensure that the decrement button in your React component stops at zero and does not go into negative values, you need to add a condition to check if the value is greater than zero before decrementing it. You also need to handle the case where the item is not in the cart yet. Here’s how you can modify your handleDeleteToCart function to achieve this:

    import React, { useState } from 'react';
    
    const YourComponent = () => {
    const [cart, setCart] = useState({});
    
    const handleAddToCart = (item) => {
    setCart((prev) => ({ ...prev, [item.id]: (prev[item.id] || 0) + 1 }));
    };
    
    const handleDeleteToCart = (item) => {
    setCart((prev) => {
      const currentCount = prev[item.id] || 0;
      if (currentCount > 0) {
        return { ...prev, [item.id]: currentCount - 1 };
      }
      return prev;
    });
    };
    
      return (
    <div>
      {/* Your card components */}
      {Object.keys(cart).map((key) => (
        <div key={key}>
          <p>Item: {key}</p>
          <p>Quantity: {cart[key]}</p>
          <button onClick={() => handleAddToCart({ id: key })}>Add</button>
          <button onClick={() => handleDeleteToCart({ id: key })}>Remove</button>
        </div>
      ))}
    </div>
     );
    };
    
    export default YourComponent;
    
    Login or Signup to reply.
  2. Try the below it will work

    const handleDeleteToCart = (itemId) => {
      setCart((prevCart) => {
        const currentQuantity = prevCart[itemId] || 0;
        if (currentQuantity > 0) {
          return {...prevCart, [itemId]: currentQuantity - 1 };
        }
        return prevCart; // Return the original cart if the quantity is already 0
      });
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search