-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.ts
39 lines (36 loc) · 1 KB
/
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 { Product } from "./typings/productTypings";
// import type {} from '@redux-devtools/extension' // required for devtools typing
interface CartState {
cart: Product[];
addToCart: (product: Product) => void;
removeFromCart: (product: Product) => void;
}
export const useCartStore = create<CartState>()(
devtools(
persist(
(set, get) => ({
cart: [],
addToCart: (product) => {
set((state) => ({
cart: [...state.cart, product],
}));
},
removeFromCart: (product) => {
const productToRemove = get().cart.findIndex(
(p) => p.meta.sku === product.meta.sku
);
set((state) => {
const newCart = [...state.cart];
newCart.splice(productToRemove, 1);
return { cart: newCart };
});
},
}),
{
name: "shopping-cart-storage",
}
)
)
);