-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.ts
107 lines (102 loc) · 3.04 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { AddCartType } from "./types/AddCartType";
type CartState = {
isOpen: boolean;
cart: AddCartType[];
toggleCart: () => void;
clearCart: () => void;
addProduct: (item: AddCartType) => void;
removeProduct: (item: AddCartType) => void;
paymentIntent: string;
onCheckout: string;
setPaymentIntent: (val: string) => void;
setCheckout: (val: string) => void;
};
// type CartItem = {
// name: string;
// id: string;
// images?: string[];
// description?: string;
// unit_amount: number;
// quantity: number;
// };
export const useCartStore = create<CartState>()(
persist(
(set) => ({
cart: [],
isOpen: false,
paymentIntent: "",
onCheckout: "cart",
toggleCart: () => set((state) => ({ isOpen: !state.isOpen })),
addProduct: (item) =>
set((state) => {
const existingItem = state.cart.find(
(cartItem) => cartItem.id === item.id
);
if (existingItem) {
const updatedCart = state.cart.map((cartItem) => {
if (cartItem.id === item.id) {
return {
...cartItem,
quantity: (cartItem.quantity as number) + 1,
};
}
return cartItem;
});
return { cart: updatedCart };
} else {
return { cart: [...state.cart, { ...item, quantity: 1 }] };
}
}),
removeProduct: (item) =>
set((state) => {
const existingItem = state.cart.find(
(cartItem) => cartItem.id === item.id
);
// check if the item exists and decreases the quantity to 1
if (existingItem && (existingItem.quantity as number) > 1) {
const updatedCart = state.cart.map((cartItem) => {
if (cartItem.id === item.id) {
return {
...cartItem,
quantity: (cartItem.quantity as number) - 1,
};
}
return cartItem;
});
return { cart: updatedCart };
} else {
// remove item from our cart
// filter out the items in cart that have
// the id differ from the item we are going to remove
const filteredCart = state.cart.filter(
(cartItem) => cartItem.id !== item.id
);
return { cart: filteredCart };
}
}),
setPaymentIntent: (val) => set((state) => ({ paymentIntent: val })),
setCheckout: (val) => set((state) => ({ onCheckout: val })),
clearCart: () => set((state) => ({ cart: [] })),
}),
{
name: "cart-store",
}
)
);
type ThemeState = {
mode: "light" | "dark";
toggleMode: (theme: "light" | "dark") => void;
};
export const useThemeStore = create<ThemeState>()(
persist(
(set) => ({
mode: "light",
toggleMode: (theme) => set((state) => ({ mode: theme })),
}),
{
name: "theme-store",
}
)
);