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
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.
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: