1

I'm building a shopping cart, and my cart products array comes from a state. When I press the 'add to cart button, this function occurs(Infos is where the product Infos are):

const [cart, setCart] = useState([])
function addToCart() {
   setCart( arr => [...arr, {
     name: infos[id-2].fullName,
     value: infos[id-2].value,
     id: infos[id-2].id
}])}

And it's working fine, but I have repeating IDs on the cart array. This has implications on the checkout page and etc. So I need to create a new array from the cart with all the cart items, but excluding the repeated items, something like this:

const newCart = [{
   id: cart.id
   name: cart.name
   quantity: '' >times the id occurs on the cart array
   price: cart.value
   totalPrice: cart.value * quantity
}]

How can I do so? I'm using context to manage all my states

Raju Ahmed
  • 1,282
  • 5
  • 15
  • 24
unknwDev
  • 29
  • 3

1 Answers1

1

Why put duplicate ids on the cart in first place, You can include one more field in the cart object and update that only.

const cart = [{ name: "A", value: 100, id: 1, quantity: 1 }];

function addToCart() {
  const item = infos[id - 2];
  setCart((arr) => {
    const newCart = [...arr];
    const existingItem = newCart.find((i) => i.id === item.id);
    if (existingItem) {
      existingItem.quantity++;
    } else {
      newCart.push({
        name: item.fullName,
        value: item.value,
        id: item.id,
        quantity: 1,
      });
    }
    return newCart;
  });
}
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37