“I’m having an issue where, when I add an item to the cart, it seems to be adding all items at once, instead of just the one I clicked on.”
FoodItem.jsx File ->
import React, { useContext } from 'react'
import './FoodItem.css'
import { assets } from '../../assets/assets'
import { StoreContext } from '../../context/StoreContext'
const FoodItem = ({id, name, price, description, image}) => {
const {cartItems,addToCart,removeFromCart} = useContext(StoreContext);
return (
<div className='food-item'>
<div className="food-item-img-container">
<img className='food-item-image' src={image} alt=''></img>
{
!cartItems[id]
?<img className="add" onClick={() => addToCart(id)} src={assets.add_icon_white} alt=''></img>
:<div className='food-item-counter'>
<img onClick={()=>removeFromCart(id)} src={assets.remove_icon_red} alt="" />
<p>{cartItems[id]}</p>
<img onClick={()=>addToCart(id)} src={assets.add_icon_green} alt=''></img>
</div>
}
</div>
<div className="food-item-info">
<div className="food-item-name-rating">
<p>{name}</p>
<img src={assets.rating_starts} alt=''></img>
</div>
<p className="food-item-desc">
{description}
</p>
<p className="food-item-price">
₹{price}
</p>
</div>
</div>
)
}
export default FoodItem
StoreContext.jsx File ->
import { createContext, useEffect, useState } from "react";
import { food_list } from "../assets/assets";
export const StoreContext = createContext({});
const StoreContextProvider = (props) => {
const [cartItems, setCartItems] = useState({});
const addToCart = (itemId) => {
if(!cartItems[itemId]){
setCartItems((prev)=>({...prev,[itemId]:1}))
}
else{
setCartItems((prev)=>({...prev,[itemId]:prev[itemId]+1}))
}
}
const removeFromCart = (itemId) => {
setCartItems((prev)=>({...prev,[itemId]:prev[itemId]-1}))
}
useEffect(() => {
console.log(cartItems)
},[cartItems])
const contextValue = {
food_list,
cartItems,
setCartItems,
addToCart,
removeFromCart
}
return (
<StoreContext.Provider value={contextValue}>
{props.children}
</StoreContext.Provider>
)
}
export default StoreContextProvider;
I tried checking the addToCart function to ensure that it’s only updating the state for the specific item I clicked on. I also reviewed the component to make sure it’s correctly receiving and displaying the cartItems state. Additionally, I added a console.log to see if the itemId passed to the function matches the item being clicked.
2
Your code seems to correct and I am sure the source of the error you are having lies somewhere else.
First, make sure that each food item has a unique id.
And second, add some logs into the addtoCard function to check that the correct itemId is referred.
const addToCart = (itemId) => {
console.log("Adding item to cart: ", itemId);
if (!cartItems[itemId]) {
setCartItems((prev) => {
console.log("Previous state:", prev);
return { ...prev, [itemId]: 1 };
});
} else {
setCartItems((prev) => {
console.log("Previous state:", prev);
return { ...prev, [itemId]: prev[itemId] + 1 };
});
}`enter code here`
};
And you could refine the function like this. it may help.
const addToCart = (itemId) => {
setCartItems((prev) => {
const updatedCartItems = { ...prev }; // Clone the previous state
updatedCartItems[itemId] = (updatedCartItems[itemId] || 0) + 1;
return updatedCartItems;
});
};