-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
CartContext.js
50 lines (41 loc) · 1.17 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
import React, {createContext, useState} from 'react';
import { getProduct } from './services/ProductsService.js';
export const CartContext = createContext();
export function CartProvider(props) {
const [items, setItems] = useState([]);
function addItemToCart(id) {
const product = getProduct(id);
setItems((prevItems) => {
const item = prevItems.find((item) => (item.id == id));
if(!item) {
return [...prevItems, {
id,
qty: 1,
product,
totalPrice: product.price
}];
}
else {
return prevItems.map((item) => {
if(item.id == id) {
item.qty++;
item.totalPrice += product.price;
}
return item;
});
}
});
}
function getItemsCount() {
return items.reduce((sum, item) => (sum + item.qty), 0);
}
function getTotalPrice() {
return items.reduce((sum, item) => (sum + item.totalPrice), 0);
}
return (
<CartContext.Provider
value={{items, setItems, getItemsCount, addItemToCart, getTotalPrice}}>
{props.children}
</CartContext.Provider>
);
}