hello I've been having a problem with checking if an item already exists in the cart. if so I want only the quantity to be updated for some reason it keeps adding the item as a new item even if it exists. This is what I've been doing:
// Adding Items to cart
const onAdd = (product, quantity) => {
const checkProductInCart = cartItemsFromLocalStorage.find((item) => item.id === product.id);
setTotalPrice((prevTotalPrice) => (prevTotalPrice + Math.round((product.price * quantity)*100)/100));
setTotalQuantities((prevTotalQuantities) => prevTotalQuantities + quantity);
if(checkProductInCart) {
// eslint-disable-next-line
const updatedCartItems = cartItemsFromLocalStorage.map((cartProduct) => {
if(cartProduct.id === product.id) return {
...cartProduct,
quantity: cartProduct.quantity + quantity
}
})
setCartItems(updatedCartItems);
} else {
product.quantity = quantity;
setCartItems([{ ...product }, ...cartItems]);
}
toast.success(` ${product.name} added to the cart.`);
}