0

I am using add to cart function and I am successfully getting the item in my cart on the first click. It just won't increment when I add multiple objects in the cart. It is just displaying one item on a click. The length and the qty of the array always remains 1.

 const Card = (props) => {

  const { product } = props;

  const [isActive, setIsActive] = useState(true);

  const [quantity, setQuantity] = useState(1);

  const [cart, setCart] = useState([]);

  const handleDecrement = () => {
    if (quantity > 1) {
      setQuantity((prevCount) => prevCount - 1);
    } else if (quantity === 1) {
      setIsActive(true);
    }
  };

  const handleIncrement = () => {
    if (quantity < 5) {
      setQuantity((prevCount) => prevCount + 1);
      addToCart(product);
    }
  };

  const addToCart = (product) => {
    const exist = cart.find((x) => x.id === product.id);
    if (exist) {
      setCart(
        cart.map((x) =>
          x.id === product.id ? { ...exist, qty: exist.qty + 1 } : x
        )
      );
    } else {
        setCart([...cart, {...product, qty: 1}])
    }
  };

  console.log(cart);


  return (
    <>
      <div className="card">
        <div className="product-details">
          <div className="img-container">
            <img src={product.img} alt={product.title} />
          </div>
          <div className="data-container">
            <div className="title">{product.title}</div>
            <div className="subheading">{product.subheading}</div>
            <div className="price">{product.price}</div>
          </div>
        </div>
        <div className="button">
          {isActive && (
            <button
              onClick={() => {
                setIsActive(!isActive);
                addToCart(product);
              }}
            >
              ADD
            </button>
          )}
          {isActive === false ? (
            <div className="inc">
              <span onClick={handleDecrement}>-</span>
              <span> {quantity} </span>
              <span onClick={handleIncrement}>+</span>
            </div>
          ) : null}
        </div>
      </div>
      <Footer cart={cart}/>
    </>
  );
};

Can someone tell what am I doing wrong? I've been stuck on it for a while now.

Harshil Gambhir
  • 337
  • 1
  • 2
  • 8
  • I ran your code and it works fine, `qty` changes as expected. – Konrad Aug 04 '22 at 21:51
  • I also ran your code and it seems to work fine. Here is a link so you can see for yourself it is working https://stackblitz.com/edit/react-eztdio?file=src%2FApp.js,src%2FCard.js – Rocky Sims Aug 04 '22 at 21:55
  • but when I run it and check my console, the qty doesn't increase. Here's the link to my repository https://github.com/gambhir-harshil/Daalchini – Harshil Gambhir Aug 04 '22 at 22:16
  • and if I add another object in the cart the array shows only the other object i added and deletes the previous one. – Harshil Gambhir Aug 04 '22 at 22:19
  • 2
    The issue is that each product has its own `Card` component so you actually have a separate cart for each product. The old product isn't being deleted, it's just a different `cart` array. – Rocky Sims Aug 04 '22 at 22:32
  • How do I fix it? – Harshil Gambhir Aug 04 '22 at 22:33
  • 1
    You need to lift the `cart` state up into the parent component. Remove `const [cart, setCart] = useState([]);` from the `Card` component and instead put it in the `App` component. Then add `cart={cart} setCart={setCart}` to the `Card` component's attributes (props) so that all the `Card` components are using the same `cart` array. Also, in the `Card` component, change `const { product } = props;` to `const { product, cart, setCart } = props;`. – Rocky Sims Aug 04 '22 at 22:47

0 Answers0