skip to Main Content

There is a function "addToCart" that I’m using to show the content of a cart, but i’m getting duplicates.

How can I prevent this.

    function addToCart (product, count) {

    const newCart = cart.map((item) => item);
    const newItemInCart = { count, ...product };
    newCart.push(newItemInCart);
    setCart(newCart);

    }

Idk how to start doing it

2

Answers


  1. check if the product already exists in the cart before adding it. If the product already exists, you can update its count instead of adding a new entry.

    function addToCart(product, count) {
      // Check if the product already exists in the cart
      const existingItemIndex = cart.findIndex(
        (item) => item.id === product.id
      );
    
      if (existingItemIndex !== -1) {
        // Product already exists in the cart, update the count
        const newCart = cart.map((item, index) => {
          if (index === existingItemIndex) {
            return {
              ...item,
              count: item.count + count,
            };
          } else {
            return item;
          }
        });
    
        setCart(newCart);
      } else {
        // Product doesn't exist in the cart, add it as a new item
        const newItemInCart = { count, ...product };
        const newCart = [...cart, newItemInCart];
        setCart(newCart);
      }
    }
    
    Login or Signup to reply.
  2. To prevent duplicates in your cart, you need to check if the product already exists in the cart before adding it. If it exists, you can simply increase the count of that product, otherwise, you add the product as a new item. Here’s how you can do it:

    function addToCart(product: ProductType, count: number): void {
      const existingProductIndex = cart.findIndex((item) => item.id === product.id);
    
      if (existingProductIndex >= 0) {
        const newCart = [...cart];
        newCart[existingProductIndex].count += count;
        setCart(newCart);
      } else {
        const newItemInCart = { count, ...product };
        setCart((prevCart) => [...prevCart, newItemInCart]);
      }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search