-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.js
50 lines (45 loc) · 1.02 KB
/
store.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
export const initialState={
cart:[],
orders:[],
};
// action
// {
// type:'ADD _PRODUCT_TO_CART',
// payload:{}
// }
export const reducer=(state=initialState,action)=>{
switch(action.type){
case "ADD_TO_CART":{
const {cart}=state;
const updatedCart=[...cart,action.payload];
//some action on state
return{ //returning the updated state;
...state,
cart:updatedCart,
}
}
case "REMOVE_FROM_CART":{
const productIdToBeRemove=action.payload.pid;
const {cart}=state;
const filteredCart=cart.filter(item => (item.id!==productIdToBeRemove))
return{
...state,
cart:filteredCart,
}
}
case "PLACE_ORDER":{
const {cart,orders}=state;
const ordersPlaced = {};
cart.forEach((item)=>{
ordersPlaced[item.id]=item;
})
const updatedOrders=[...orders,ordersPlaced];
return {
...state,
orders:updatedOrders,
cart:[],
}
}
default:return state;
}
}