forked from topcoder-platform/community-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data-fetch.js
57 lines (52 loc) · 1.57 KB
/
data-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
/**
* Reducer for state.example.dataFetch
*/
import actions from 'actions/examples/data-fetch';
import { redux } from 'topcoder-react-utils';
/**
* Handles examples.dataFetch.fetchDataDone action.
* @param {Object} state Previous state.
* @param {Object} action Action.
*/
function onDone(state, action) {
return {
...state,
data: action.error ? null : action.payload,
failed: action.error,
loading: false,
};
}
/**
* Creates a new dataFetch reducer with the specified initial state.
* @param {Object} initialState Optional. Initial state.
* @return dataFetch reducer.
*/
function create(initialState) {
return redux.handleActions({
[actions.examples.dataFetch.fetchDataInit](state) {
return {
...state,
data: null,
failed: false,
loading: true,
};
},
[actions.examples.dataFetch.fetchDataDone]: onDone,
}, initialState || {});
}
/**
* Factory which creates a new reducer with its initial state tailored to the
* ExpressJS HTTP request, if specified (for efficient server-side rendering).
* If HTTP request is not specified, it creates just the default reducer.
* @param {Object} req Optional. ExpressJS HTTP request.
* @return Promise which resolves to the new reducer.
*/
export function factory(req) {
if (req && req.url.endsWith('/examples/data-fetch/server')) {
return redux.resolveAction(actions.examples.dataFetch.fetchDataDone())
.then(res => create(onDone({}, res)));
}
return Promise.resolve(create());
}
/* Default reducer with empty initial state. */
export default create();