I made e-commerce with a cart for activity using context API, but, when I am going to remove an item from the cart and I have two of them but when I remove one, I remove the other one. How to avoid it?
Inside my providers, this is my catalogue:
import { createContext, useState } from "react"
export const CatalogueContext = createContext([])
export const CatalogueProvider = ({ children }) => {
const [catalogue, setCatalogue] = useState([
{id: 1, name: "Affogato", price: 10, img: affogato,},
{id: 2, name: "Café preto", price: 10, img: black,},
{id: 3, name: "Capuccino", price: 10, img: cappuccino,},
{id: 4, name: "Dalgona", price: 10, img: dalgona,},
{id: 5, name: "Doppio", price: 10, img: doppio,},
{id: 6, name: "Expresso", price: 10, img: expresso,},
{id: 7, name: "Galão", price: 10, img: galao,},
{id: 8, name: "Irlandês", price: 10, img: irish},
{id: 9, name: "Latte", price: 10, img: latte,},
{id: 10, name: "Mocha", price: 10, img: mocha,}
])
return (
<CatalogueContext.Provider value={{ catalogue }} >
{children}
</CatalogueContext.Provider>
)
}
This is my cart:
import { createContext, useState } from "react";
export const CartContext = createContext([])
export const CartProvider = ({ children }) => {
const [cart, setCart] = useState([])
const addToCart = (item) => {
setCart([...cart, item])
}
const removeFromCart = (item) => {
const newCart = cart.filter((itemOnCart) => itemOnCart.id !== item.id)
setCart(newCart)
}
return (
<CartContext.Provider value={{ cart, addToCart, removeFromCart}} >
{children}
</CartContext.Provider>
)
}
Can you try to use property for store a count of items in cart. For example: When user add first item you add it in array When user try to add the same item, you need to update count for 1
Method map will help you
Same logic for removing. When user removes any item, you will find it in array and decrement counter. When counter will equal 0 - remove it from array
Method find will help you with whis