-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathstore.ts
86 lines (82 loc) · 2.56 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
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
}
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! + 1 }
}
return cartItem
})
return { cart: updatedCart }
} else {
return { cart: [...state.cart, { ...item, quantity: 1 }] }
}
}),
removeProduct: (item) =>
set((state) => {
//Check if the item exists and remove quantity - 1
const existingItem = state.cart.find(
(cartItem) => cartItem.id === item.id
)
if (existingItem && existingItem.quantity! > 1) {
const updatedCart = state.cart.map((cartItem) => {
if (cartItem.id === item.id) {
return { ...cartItem, quantity: cartItem.quantity! - 1 }
}
return cartItem
})
return { cart: updatedCart }
} else {
//Remove item from cart
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" }
)
)