-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcartStore.js
More file actions
executable file
·72 lines (64 loc) · 2.19 KB
/
cartStore.js
File metadata and controls
executable file
·72 lines (64 loc) · 2.19 KB
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
import { create } from "zustand";
const useCartStore = create((set) => ({
cart: [],
cartTotal: 0,
totalItems: 0,
addToCart: ({ product, quantity }) =>
set((state) => {
const existingProductIndex = state.cart.findIndex(
(item) => item._id === product._id
);
const newQuantity = parseInt(quantity, 10);
if (newQuantity <= 0) {
// If the new quantity is less than or equal to zero, remove the item from the cart
const updatedCart = state.cart.filter(
(item) => item._id !== product._id
);
return {
cart: updatedCart,
cartTotal: calculateCartTotal(updatedCart),
totalItems: calculateTotalItems(updatedCart),
};
}
if (existingProductIndex !== -1) {
// If the product already exists, update the quantity to the new quantity
const updatedCart = [...state.cart];
updatedCart[existingProductIndex].quantity = newQuantity;
return {
cart: updatedCart,
cartTotal: calculateCartTotal(updatedCart),
totalItems: calculateTotalItems(updatedCart),
};
} else {
// If the product doesn't exist, add it to the cart with the new quantity
return {
cart: [...state.cart, { ...product, quantity: newQuantity }],
cartTotal: calculateCartTotal([
...state.cart,
{ ...product, quantity: newQuantity },
]),
totalItems: calculateTotalItems([
...state.cart,
{ ...product, quantity: newQuantity },
]),
};
}
}),
removeFromCart: (productId) =>
set((state) => {
const updatedCart = state.cart.filter((item) => item._id !== productId);
return {
cart: updatedCart,
cartTotal: calculateCartTotal(updatedCart),
totalItems: calculateTotalItems(updatedCart),
};
}),
clearCart: () => set({ cart: [], cartTotal: 0, totalItems: 0 }),
}));
function calculateCartTotal(cart) {
return cart.reduce((total, item) => total + item.price * item.quantity, 0);
}
function calculateTotalItems(cart) {
return cart.reduce((total, item) => total + 1, 0);
}
export default useCartStore;