React Issue – Multiple items will be add in Cart

“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;
    });
};

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật