CartContext.jsx
3.66 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
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import React, { createContext, useContext, useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
// Create a context for the cart
const CartContext = createContext();
// Custom hook to use the cart context
export const useCart = () => {
const context = useContext(CartContext);
if (!context) {
throw new Error('useCart must be used within a CartProvider');
}
return context;
};
// Cart provider component
export const CartProvider = ({ children }) => {
const [cartItems, setCartItems] = useState([]);
const navigate = useNavigate();
// Load cart from localStorage on component mount
useEffect(() => {
const storedCart = localStorage.getItem('cart');
if (storedCart) {
try {
setCartItems(JSON.parse(storedCart));
} catch (error) {
console.error('Failed to parse cart from localStorage:', error);
// Reset cart if there's an error
localStorage.removeItem('cart');
}
}
}, []);
// Save cart to localStorage whenever it changes
useEffect(() => {
localStorage.setItem('cart', JSON.stringify(cartItems));
}, [cartItems]);
// Add an item to the cart
const addToCart = (item) => {
setCartItems(prevItems => {
// Check if item already exists in cart
const existingItemIndex = prevItems.findIndex(i =>
i.id === item.id && i.type === item.type
);
if (existingItemIndex >= 0) {
// Item exists, update the quantity
const updatedItems = [...prevItems];
updatedItems[existingItemIndex] = {
...updatedItems[existingItemIndex],
quantity: updatedItems[existingItemIndex].quantity + 1
};
return updatedItems;
} else {
// Item doesn't exist, add it with quantity 1
return [...prevItems, { ...item, quantity: 1 }];
}
});
};
// Remove an item from the cart
const removeFromCart = (itemId, itemType) => {
setCartItems(prevItems =>
prevItems.filter(item => !(item.id === itemId && item.type === itemType))
);
};
// Update quantity of an item in the cart
const updateQuantity = (itemId, itemType, quantity) => {
if (quantity < 1) return;
setCartItems(prevItems =>
prevItems.map(item =>
(item.id === itemId && item.type === itemType)
? { ...item, quantity }
: item
)
);
};
// Clear the entire cart
const clearCart = () => {
setCartItems([]);
};
// Get the number of items in cart
const getItemCount = () => {
return cartItems.reduce((total, item) => total + item.quantity, 0);
};
// Calculate the total price of items in the cart
const getTotalPrice = () => {
return cartItems.reduce(
(total, item) => total + (item.price * item.quantity),
0
);
};
// Proceed to checkout
const proceedToCheckout = () => {
if (cartItems.length > 0) {
navigate('/checkout');
}
};
// Handle the checkout process
const handleCheckout = (userData) => {
// In a real application, this would send the order to a backend
console.log('Processing order with data:', { items: cartItems, userData });
// Simulating successful checkout
return new Promise((resolve) => {
setTimeout(() => {
clearCart();
resolve({ success: true, orderId: 'ORD-' + Date.now() });
}, 1500);
});
};
// Values to provide in the context
const value = {
cartItems,
addToCart,
removeFromCart,
updateQuantity,
clearCart,
getItemCount,
getTotalPrice,
proceedToCheckout,
handleCheckout
};
return (
<CartContext.Provider value={value}>
{children}
</CartContext.Provider>
);
};