Zustand help

I have this code, it is a cart system. It works fine but The problem I have is that when updating an item with the same properties as existign item it makes another item instead of just updating quantity, works as it should with addItem but when i apply the same logic to updateItem it does not work
1 Reply
fdawg
fdawgOP14mo ago
export interface Pizza { id: number; quantity: number; size: string; toppings: string[]; price: number; } import { create } from "zustand"; import { persist, createJSONStorage } from "zustand/middleware"; import { toast } from "sonner"; import { Pizza } from "@/types"; interface CartStore { items: Pizza[]; addItem: (data: Pizza) => void; removeItem: (id: string) => void; updateItem: (updatedItem: Pizza) => void; removeAll: () => void; } const useCart = create( persist<CartStore>( (set, get) => ({ items: [], addItem: (data: Pizza) => { const currentItems = get().items; const existingItem = currentItems.find( (item) => item.size === data.size && JSON.stringify(item.toppings.sort()) === JSON.stringify(data.toppings.sort()), ); if (existingItem) { existingItem.quantity += data.quantity; } else { const newItem: Pizza = { ...data }; currentItems.push(newItem); } set({ items: [...currentItems] }); toast.success("Item added to cart."); }, removeItem: (id: string) => { set({ items: [ ...get().items.filter( (item) => item.id.toString() !== id.toString(), ), ], }); toast.error("Item removed from cart."); }, updateItem: (updatedItem: Pizza) => { set({ items: get().items.map((item) => { if (item.id === updatedItem.id) { return updatedItem; } return item; }), }); toast.success("Item updated in cart."); }, removeAll: () => set({ items: [] }), }), { name: "cart-storage", storage: createJSONStorage(() => localStorage), }, ), ); export default useCart;
Want results from more Discord servers?
Add your server