-
Notifications
You must be signed in to change notification settings - Fork 12.4k
Expand file tree
/
Copy pathCartProvider.js
More file actions
89 lines (75 loc) · 2.23 KB
/
Copy pathCartProvider.js
File metadata and controls
89 lines (75 loc) · 2.23 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
import { useReducer } from 'react';
import CartContext from './cart-context';
const defaultCartState = {
items: [],
totalAmount: 0,
};
const cartReducer = (state, action) => {
if (action.type === 'ADD') {
const updatedTotalAmount =
state.totalAmount + action.item.price * action.item.amount;
const existingCartItemIndex = state.items.findIndex(
(item) => item.id === action.item.id
);
const existingCartItem = state.items[existingCartItemIndex];
let updatedItems;
if (existingCartItem) {
const updatedItem = {
...existingCartItem,
amount: existingCartItem.amount + 1,
};
updatedItems = [...state.items];
updatedItems[existingCartItemIndex] = updatedItem;
} else {
updatedItems = state.items.concat(action.item);
}
return {
items: updatedItems,
totalAmount: updatedTotalAmount,
};
}
if (action.type === 'REMOVE') {
const existingCartItemIndex = state.items.findIndex(
(item) => item.id === action.id
);
const existingItem = state.items[existingCartItemIndex];
const updatedTotalAmount = state.totalAmount - existingItem.price;
let updatedItems;
if (existingItem.amount === 1) {
updatedItems = state.items.filter(item => item.id !== action.id);
} else {
const updatedItem = { ...existingItem, amount: existingItem.amount - 1 };
updatedItems = [...state.items];
updatedItems[existingCartItemIndex] = updatedItem;
}
return {
items: updatedItems,
totalAmount: updatedTotalAmount
};
}
return defaultCartState;
};
const CartProvider = (props) => {
const [cartState, dispatchCartAction] = useReducer(
cartReducer,
defaultCartState
);
const addItemToCartHandler = (item) => {
dispatchCartAction({ type: 'ADD', item: item });
};
const removeItemFromCartHandler = (id) => {
dispatchCartAction({ type: 'REMOVE', id: id });
};
const cartContext = {
items: cartState.items,
totalAmount: cartState.totalAmount,
addItem: addItemToCartHandler,
removeItem: removeItemFromCartHandler,
};
return (
<CartContext.Provider value={cartContext}>
{props.children}
</CartContext.Provider>
);
};
export default CartProvider;