fdawg
fdawg
TTCTheo's Typesafe Cult
Created by fdawg on 10/28/2023 in #questions
Zustand help
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;
3 replies
TTCTheo's Typesafe Cult
Created by fdawg on 10/27/2023 in #questions
Persisting state across Next.js pages
Thanks for reply, I ended up by using zustand with persistance , works perfectly!
5 replies