Spaces:
Running
Running
Create store/cart-store.ts
Browse files- store/cart-store.ts +42 -0
store/cart-store.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// store/cart-store.ts
|
| 2 |
+
import { create } from 'zustand';
|
| 3 |
+
import { persist } from 'zustand/middleware';
|
| 4 |
+
|
| 5 |
+
export interface CartItem {
|
| 6 |
+
id: string;
|
| 7 |
+
name: string;
|
| 8 |
+
price: number;
|
| 9 |
+
quantity: number;
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
interface CartState {
|
| 13 |
+
items: CartItem[];
|
| 14 |
+
addItem: (item: Omit<CartItem, 'quantity'>) => void;
|
| 15 |
+
removeItem: (id: string) => void;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
// ⚡ [OTIMIZAÇÃO DE PERFORMANCE/INP]: Zustand com persistência automática no LocalStorage.
|
| 19 |
+
export const useCartStore = create<CartState>()(
|
| 20 |
+
persist(
|
| 21 |
+
(set) => ({
|
| 22 |
+
items: [],
|
| 23 |
+
addItem: (newItem) => set((state) => {
|
| 24 |
+
const existingItem = state.items.find((i) => i.id === newItem.id);
|
| 25 |
+
if (existingItem) {
|
| 26 |
+
return {
|
| 27 |
+
items: state.items.map((i) =>
|
| 28 |
+
i.id === newItem.id ? { ...i, quantity: i.quantity + 1 } : i
|
| 29 |
+
),
|
| 30 |
+
};
|
| 31 |
+
}
|
| 32 |
+
return { items: [...state.items, { ...newItem, quantity: 1 }] };
|
| 33 |
+
}),
|
| 34 |
+
removeItem: (id) => set((state) => ({
|
| 35 |
+
items: state.items.filter((i) => i.id !== id)
|
| 36 |
+
})),
|
| 37 |
+
}),
|
| 38 |
+
{
|
| 39 |
+
name: 'ecommerce-cart-storage', // Chave do LocalStorage
|
| 40 |
+
}
|
| 41 |
+
)
|
| 42 |
+
);
|