Azeem Ansari
Azeem Ansari

Reputation: 47

How to update cart quantity if item already exist in Cart - reactjs?

in this code, instead of showing "The product has been added to cart." alert message, I want to update cart quantity if item already exist in cart, please help me out.

const addToCart = (id) => {
    const check = cart.every((item) => {
      return item.id !== id;
    });
    if (check) {
      const cartData = products.filter((el) => {
        return el.id === id;
      });
      setCart([...cart, ...cartData]);
    } else {
      alert('The product has been added to cart.');
    }

Upvotes: 0

Views: 2467

Answers (2)

STaigertw
STaigertw

Reputation: 19

try something similar to the approach bellow:

   const addToCart = (id) => {
  const check = cart.every((item) => {
    return item.id !== id;
  });
  const cartData = products.filter((el) => {
    return el.id === id;
  });
  if (check) {
    setCart([...cart, ...cartData]);
  } else {
    const itemForCountIncrease = cart.find((item) => item.id == id);
    itemForCountIncrease.count += 1;
    setCart([...cart.filter((item) => item.id != id), itemForCountIncrease]);
  }
};

Upvotes: 0

codemonkey
codemonkey

Reputation: 7915

I am making some assumptions here as to what your variables look like, but generally, here is what you need:

const products = [{id: 1, name: 'Prod 1'}, {id: 2, name: 'Prod 2'}, {id: 3, name: 'Prod 3'}, {id: 4, name: 'Prod 4'}]
const cart = [{id: 1, name: 'Prod 1', quantity: 1}, {id: 4, name: 'Prod 4', quantity: 1}];

const addToCart = (id) => {
    const check_index = cart.findIndex(item => item.id === id);
    if (check_index !== -1) {
      cart[check_index].quantity++;
      console.log("Quantity updated:", cart);
    } else {
      cart.push({...products.find(p => p.id === id), quantity: 1})
      console.log('The product has been added to cart:', cart);
    }
}

addToCart(4)

Upvotes: 4

Related Questions