forked from vcrabtree/GroceryStoreApp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ItemsReducer.js
62 lines (50 loc) · 1.55 KB
/
ItemsReducer.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
51
52
53
54
55
56
57
58
59
60
61
62
import { combineReducers } from 'redux';
const INITIAL_STATE = {
current: [
],
possible: [
'Apple',
'Pear',
'Banana',
'Carrot',
'Lettuce',
'Milk'
],
};
const itemsReducer = (state = INITIAL_STATE, action) => {
const {
current,
possible,
} = state;
switch (action.type) {
case 'ADD_ITEM':
// Pulls current and possible out of previous state
// We do not want to alter state directly in case
// another action is altering it at the same time
// Pull friend out of friends.possible
// Note that action.payload === friendIndex
const addedItem = possible.splice(action.payload, 1);
// And put friend in friends.current
const newItem = {key: current.length.toString(), groceryItem: addedItem}
current.push(newItem);
// Finally, update the redux state
const newState = { current, possible };
return newState;
case 'REMOVE_ITEM':
// Get the index in the current array of the friend to remove
const removedItem = current[action.payload].groceryItem;
// Use the splice function in JavaScript to take the friend
// out of the current array and to get the name of the removed friend
const removedItem2 = current.splice(action.payload, 1);
// And put friend into the possible array
possible.push(removedItem);
// Finally, update the redux state
const newState2 = { current, possible };
return newState2;
default:
return state
}
};
export default combineReducers({
items: itemsReducer
});