-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreducer.js
42 lines (35 loc) · 1.06 KB
/
reducer.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
export const initialState = {
basket: [],
};
//Selector
export const getBasketTotal = (basket) =>
basket?.reduce((amount, item) => item.price + amount, 0);
const reducer = (state, action) => {
console.log(action);
switch (action.type) {
case 'ADD_TO_BASKET':
return {
...state,
basket: [...state.basket, action.item],
};
case "REMOVE_FROM_BASKET":
const index = state.basket.findIndex(
(basketItem) => basketItem.id === action.id
);
let newBasket = [...state.basket];
if (index >= 0) {
newBasket.splice(index, 1);
} else {
console.warn(
`Cant't remove product (id: ${action.id}) as its not in basket!`
);
}
return {
...state,
basket:newBasket
}
default:
return state;
}
};
export default reducer;