forked from larkintuckerllc/redux-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnormalizr.js
82 lines (81 loc) · 1.77 KB
/
normalizr.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
77
78
79
80
81
82
/* eslint no-console: "off" */
import { combineReducers, createStore } from 'redux';
import { normalize, schema } from 'normalizr';
const itemSchema = new schema.Entity('items');
const itemsSchema = new schema.Array(itemSchema);
const byId = (state = {}, action) => {
switch (action.type) {
case 'FETCH':
case 'ADD':
case 'UPDATE': {
return {
...state,
...action.value.entities.items,
};
}
case 'REMOVE': {
const newState = { ...state };
delete newState[action.value.result];
return newState;
}
default:
return state;
}
};
const ids = (state = [], action) => {
switch (action.type) {
case 'FETCH':
return action.value.result;
case 'ADD':
return [...state, action.value.result];
case 'REMOVE': {
const newState = [...state];
newState.splice(state.indexOf(action.value.result), 1);
return newState;
}
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: normalize(
[{
id: 'm',
name: 'mango',
description: 'Sweet and sticky',
}, {
id: 'n',
name: 'nectarine',
description: 'Crunchy goodness',
}],
itemsSchema,
),
});
store.dispatch({
type: 'UPDATE',
value: normalize(
{
id: 'm',
name: 'mango',
description: 'Sweet and super sticky',
},
itemSchema,
),
});