-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.ts
39 lines (34 loc) · 897 Bytes
/
store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { create } from "zustand";
import { devtools, persist } from "zustand/middleware";
import { ProductContent } from "./typings/productTypings";
interface CartState {
cart: ProductContent[];
addToCart: (product: ProductContent) => void;
removeFromCart: (product: ProductContent) => void;
}
const useCartStore = create<CartState>()(
devtools(
persist(
(set, get) => ({
cart: [],
addToCart: (product) =>
set((state) => ({ cart: [...state.cart, product] })),
removeFromCart: (product) => {
const productToRemove = get().cart.findIndex(
(item) =>
item.content.meta.sku === product.content.meta.sku
);
set((state) => {
const newCart = [...state.cart];
newCart.splice(productToRemove, 1);
return { cart: newCart };
});
},
}),
{
name: "shopping-cart-storage",
}
)
)
);
export default useCartStore;