-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
widgets.js
112 lines (105 loc) · 2.52 KB
/
widgets.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
106
107
108
109
110
111
112
const LOAD = 'redux-example/widgets/LOAD';
const LOAD_SUCCESS = 'redux-example/widgets/LOAD_SUCCESS';
const LOAD_FAIL = 'redux-example/widgets/LOAD_FAIL';
const EDIT_START = 'redux-example/widgets/EDIT_START';
const EDIT_STOP = 'redux-example/widgets/EDIT_STOP';
const SAVE = 'redux-example/widgets/SAVE';
const SAVE_SUCCESS = 'redux-example/widgets/SAVE_SUCCESS';
const SAVE_FAIL = 'redux-example/widgets/SAVE_FAIL';
const initialState = {
loaded: false,
editing: {},
saveError: {}
};
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case LOAD:
return {
...state,
loading: true
};
case LOAD_SUCCESS:
return {
...state,
loading: false,
loaded: true,
data: action.result,
error: null
};
case LOAD_FAIL:
return {
...state,
loading: false,
loaded: false,
data: null,
error: action.error
};
case EDIT_START:
return {
...state,
editing: {
...state.editing,
[action.id]: true
}
};
case EDIT_STOP:
return {
...state,
editing: {
...state.editing,
[action.id]: false
}
};
case SAVE:
return state; // 'saving' flag handled by redux-form
case SAVE_SUCCESS:
const data = [...state.data];
data[action.result.id - 1] = action.result;
return {
...state,
data: data,
editing: {
...state.editing,
[action.id]: false
},
saveError: {
...state.saveError,
[action.id]: null
}
};
case SAVE_FAIL:
return typeof action.error === 'string' ? {
...state,
saveError: {
...state.saveError,
[action.id]: action.error
}
} : state;
default:
return state;
}
}
export function isLoaded(globalState) {
return globalState.widgets && globalState.widgets.loaded;
}
export function load() {
return {
types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
promise: (client) => client.get('/widget/load/param1/param2') // params not used, just shown as demonstration
};
}
export function save(widget) {
return {
types: [SAVE, SAVE_SUCCESS, SAVE_FAIL],
id: widget.id,
promise: (client) => client.post('/widget/update', {
data: widget
})
};
}
export function editStart(id) {
return { type: EDIT_START, id };
}
export function editStop(id) {
return { type: EDIT_STOP, id };
}