-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCartContext.js
78 lines (66 loc) · 2.38 KB
/
CartContext.js
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
// src/CartContext.js
import React, { createContext, useState, useEffect } from 'react';
export const CartContext = createContext();
export const CartProvider = ({ children }) => {
const [cart, setCart] = useState([]);
const loadCartFromLocalStorage = () => {
const savedCart = localStorage.getItem('cart');
if (savedCart) {
setCart(JSON.parse(savedCart));
}
};
const saveCartToLocalStorage = (newCart) => {
localStorage.setItem('cart', JSON.stringify(newCart));
};
useEffect(() => {
loadCartFromLocalStorage();
}, []);
useEffect(() => {
saveCartToLocalStorage(cart);
}, [cart]);
const addToCart = (product) => {
setCart((prevCart) => {
const existingProduct = prevCart.find(item => item.id === product.id);
if (existingProduct) {
return prevCart.map(item =>
item.id === product.id
? { ...item, quantity: item.quantity + 1 }
: item
);
} else {
return [...prevCart, { ...product, quantity: 1 }];
}
});
};
const removeFromCart = (productId) => {
setCart((prevCart) => {
const existingProduct = prevCart.find(item => item.id === productId);
if (existingProduct && existingProduct.quantity > 1) {
return prevCart.map(item =>
item.id === productId
? { ...item, quantity: item.quantity - 1 }
: item
);
} else {
return prevCart.filter(item => item.id !== productId);
}
});
};
const updateQuantity = (productId, quantity) => {
setCart((prevCart) => {
return prevCart.map(item =>
item.id === productId
? { ...item, quantity: Math.max(1, quantity) }
: item
);
});
};
const calculateTotal = () => {
return cart.reduce((total, item) => total + item.price * item.quantity, 0);
};
return (
<CartContext.Provider value={{ cart, addToCart, removeFromCart, updateQuantity, calculateTotal }}>
{children}
</CartContext.Provider>
);
};