first commit
This commit is contained in:
77
src/store/cart-store.ts
Normal file
77
src/store/cart-store.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { create } from 'zustand';
|
||||
import { persist, createJSONStorage } from 'zustand/middleware';
|
||||
import { Product, CartItem } from '@/types';
|
||||
|
||||
interface CartState {
|
||||
items: CartItem[];
|
||||
isOpen: boolean;
|
||||
addItem: (product: Product, quantity?: number) => void;
|
||||
removeItem: (productId: string) => void;
|
||||
updateQuantity: (productId: string, quantity: number) => void;
|
||||
clearCart: () => void;
|
||||
toggleCart: () => void;
|
||||
openCart: () => void;
|
||||
closeCart: () => void;
|
||||
// Getters
|
||||
getTotalPrice: () => number;
|
||||
getTotalItems: () => number;
|
||||
}
|
||||
|
||||
export const useCartStore = create<CartState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
items: [],
|
||||
isOpen: false,
|
||||
|
||||
addItem: (product, quantity = 1) => {
|
||||
const currentItems = get().items;
|
||||
const existingItem = currentItems.find((item) => item.id === product.id);
|
||||
|
||||
if (existingItem) {
|
||||
// Si ya existe, sumamos la cantidad
|
||||
const updatedItems = currentItems.map((item) =>
|
||||
item.id === product.id
|
||||
? { ...item, quantity: item.quantity + quantity }
|
||||
: item
|
||||
);
|
||||
set({ items: updatedItems, isOpen: true }); // Abrimos el carrito al añadir
|
||||
} else {
|
||||
// Si es nuevo, lo añadimos
|
||||
set({ items: [...currentItems, { ...product, quantity }], isOpen: true });
|
||||
}
|
||||
},
|
||||
|
||||
removeItem: (id) => {
|
||||
set({ items: get().items.filter((item) => item.id !== id) });
|
||||
},
|
||||
|
||||
updateQuantity: (id, quantity) => {
|
||||
if (quantity < 1) return;
|
||||
set({
|
||||
items: get().items.map((item) =>
|
||||
item.id === id ? { ...item, quantity } : item
|
||||
),
|
||||
});
|
||||
},
|
||||
|
||||
clearCart: () => set({ items: [] }),
|
||||
|
||||
// Control de UI del Drawer
|
||||
toggleCart: () => set({ isOpen: !get().isOpen }),
|
||||
openCart: () => set({ isOpen: true }),
|
||||
closeCart: () => set({ isOpen: false }),
|
||||
|
||||
getTotalPrice: () => {
|
||||
return get().items.reduce((total, item) => total + item.price * item.quantity, 0);
|
||||
},
|
||||
|
||||
getTotalItems: () => {
|
||||
return get().items.reduce((total, item) => total + item.quantity, 0);
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: 'surtilatino-cart', // Nombre en LocalStorage
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
}
|
||||
)
|
||||
);
|
||||
Reference in New Issue
Block a user