forked from larkintuckerllc/redux-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutable.js
105 lines (104 loc) · 2.6 KB
/
mutable.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/* eslint no-console: "off" */
import { combineReducers, createStore } from 'redux';
import { normalize, schema } from 'normalizr';
import { createSelector } from 'reselect';
const itemSchema = new schema.Entity('items');
const itemsSchema = new schema.Array(itemSchema);
// REDUCERS
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,
});
// SELECTORS
const getItem = (state, id) => state.byId[id];
const getItemsIds = state => state.ids;
const getItemsById = state => state.byId;
const getItems = createSelector(
[getItemsIds, getItemsById],
(itemsIds, itemsById) => itemsIds.map(id => itemsById[id]),
);
// ACTION CREATORS
const fetch = items => ({
type: 'FETCH',
value: normalize(items, itemsSchema),
});
const update = item => ({
type: 'UPDATE',
value: normalize(item, itemSchema),
});
// STORE
const store = createStore(myReducer);
let state = store.getState();
let lastItems = getItems(state);
store.subscribe(() => {
const newState = store.getState();
const newItems = getItems(newState);
console.log(newItems === lastItems);
lastItems = newItems;
});
// EXERCISING - FETCH
store.dispatch(fetch(
[{
id: 'm',
name: 'mango',
description: 'Sweet and sticky',
}, {
id: 'n',
name: 'nectarine',
description: 'Crunchy goodness',
}],
));
// EXERCISING - OUTPUT CURRENT VALUE
state = store.getState();
let mango = getItem(state, 'm');
console.log('BEFORE UPDATE ACTION');
console.log(mango);
// EXERCISING - UPDATE PROPER
mango.description = 'Sweet and super sticky';
store.dispatch(update(mango));
// EXERCISING - OUTPUT CURRENT VALUE
state = store.getState();
mango = getItem(state, 'm');
console.log('AFTER UPDATE ACTION');
console.log(mango);
// EXCERCISING - UPDATE IMPROPER
mango.description = 'Unripe and sour';
// EXERCISING - OUTPUT CURRENT VALUE
state = store.getState();
mango = getItem(state, 'm');
console.log('AFTER IMPROPER UPDATE');
console.log(mango);