forked from larkintuckerllc/redux-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist-fetch.js
76 lines (75 loc) · 1.66 KB
/
list-fetch.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* eslint no-console: "off" */
import { combineReducers, createStore } from 'redux';
const byId = (state = {}, action) => {
switch (action.type) {
case 'ADD': {
const entry = {};
entry[action.value.id] = action.value;
return {
...state,
...entry,
};
}
case 'REMOVE': {
const newState = { ...state };
delete newState[action.value.id];
return newState;
}
case 'FETCH': {
const entry = {};
for (let i = 0; i < action.value.length; i += 1) {
const item = action.value[i];
entry[item.id] = item;
}
return {
...state,
...entry,
};
}
default:
return state;
}
};
const ids = (state = [], action) => {
switch (action.type) {
case 'ADD':
return [...state, action.value.id];
case 'REMOVE': {
const newState = [...state];
newState.splice(state.indexOf(action.value.id), 1);
return newState;
}
case 'FETCH':
return [...state, ...action.value.map(o => o.id)];
default:
return state;
}
};
const myReducer = combineReducers({
byId,
ids,
});
const store = createStore(myReducer);
const state = store.getState();
let lastById = state.byId;
let lastIds = state.ids;
store.subscribe(() => {
const newState = store.getState();
console.log(newState);
console.log(newState.byId === lastById);
console.log(newState.ids === lastIds);
lastById = newState.byId;
lastIds = newState.ids;
});
store.dispatch({
type: 'FETCH',
value: [{
id: 'm',
name: 'mango',
description: 'Sweet and sticky',
}, {
id: 'n',
name: 'nectarine',
description: 'Crunchy goodness',
}],
});