MCPcopy Create free account
hub / github.com/Source-Controller/eCommerce-Fullstack / StateContext

Function StateContext

context/StateContext.js:6–101  ·  view source on GitHub ↗
({ children })

Source from the content-addressed store, hash-verified

4const Context = createContext();
5
6export const StateContext = ({ children }) => {
7 const [showCart, setShowCart] = useState(false);
8 const [cartItems, setCartItems] = useState([]);
9 const [totalPrice, setTotalPrice] = useState(0);
10 const [totalQty, setTotalQty] = useState(0);
11 const [qty, setQty] = useState(1);
12
13 let foundProduct;
14 let index;
15
16 const onAdd = (product, quantity) => {
17 const checkProductInCart = cartItems.find((item) => item._id === product._id);
18
19 setTotalPrice((prevTotalPrice) => prevTotalPrice + product.price * quantity);
20 setTotalQty((prevTotalQty) => prevTotalQty + quantity);
21
22 if(checkProductInCart) {
23 const updatedCartItems = cartItems.map((cartProduct) => {
24 if(cartProduct._id === product._id) return {
25 ...cartProduct,
26 quantity: cartProduct.quantity + quantity
27 }
28 })
29
30 setCartItems(updatedCartItems);
31 } else {
32 product.quantity = quantity;
33
34 setCartItems([...cartItems, { ...product }]);
35 }
36
37 toast.success(`${qty} ${product.name} added to the cart.`);
38 }
39
40 const onRemove = (product) => {
41 foundProduct = cartItems.find((item) => item._id === product._id);
42 const newCartItems = cartItems.filter((item) => item._id !== product._id);
43
44 setTotalPrice((prevTotalPrice) => prevTotalPrice -foundProduct.price * foundProduct.quantity);
45 setTotalQty(prevTotalQty => prevTotalQty - foundProduct.quantity);
46 setCartItems(newCartItems);
47 }
48
49 const toggleCartItemQuantity = (id, value) => {
50 foundProduct = cartItems.find((item) => item._id === id)
51 index = cartItems.findIndex((product) => product._id === id);
52 const newCartItems = cartItems.filter((item) => item._id !== id)
53
54 if(value === 'inc') {
55 setCartItems([...newCartItems, { ...foundProduct, quantity: foundProduct.quantity + 1 } ]);
56 setTotalPrice((prevTotalPrice) => prevTotalPrice + foundProduct.price)
57 setTotalQty(prevTotalQty => prevTotalQty + 1)
58 } else if(value === 'dec') {
59 if (foundProduct.quantity > 1) {
60 setCartItems([...newCartItems, { ...foundProduct, quantity: foundProduct.quantity - 1 } ]);
61 setTotalPrice((prevTotalPrice) => prevTotalPrice - foundProduct.price)
62 setTotalQty(prevTotalQty => prevTotalQty - 1)
63 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected