Files
thermcool/lib/cart-store.ts
T

69 lines
1.7 KiB
TypeScript

import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export interface CartItem {
id: string;
slug: string;
name: string;
brand: string;
image: string;
price: number;
quantity: number;
}
interface CartState {
items: CartItem[];
addItem: (item: Omit<CartItem, 'id' | 'quantity'>) => void;
removeItem: (id: string) => void;
updateQuantity: (id: string, quantity: number) => void;
clearCart: () => void;
getTotal: () => number;
getCount: () => number;
}
export const useCartStore = create<CartState>()(
persist(
(set, get) => ({
items: [],
addItem: (newItem) => {
set((state) => {
const id = newItem.slug;
const existing = state.items.find((i) => i.id === id);
if (existing) {
return {
items: state.items.map((i) =>
i.id === id ? { ...i, quantity: i.quantity + 1 } : i
),
};
}
return { items: [...state.items, { ...newItem, id, quantity: 1 }] };
});
},
removeItem: (id) =>
set((state) => ({ items: state.items.filter((i) => i.id !== id) })),
updateQuantity: (id, quantity) => {
if (quantity < 1) return;
set((state) => ({
items: state.items.map((i) => (i.id === id ? { ...i, quantity } : i)),
}));
},
clearCart: () => set({ items: [] }),
getTotal: () => {
const { items } = get();
return items.reduce((sum, i) => sum + i.price * i.quantity, 0);
},
getCount: () => {
const { items } = get();
return items.reduce((sum, i) => sum + i.quantity, 0);
},
}),
{ name: 'thermcool-cart' }
)
);