reducers.ts
1.58 KB
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
import { sortBy, unionBy, get, set } from 'lodash/fp';
import { createReducer } from '../../helpers/Reducer';
import {fetchThreadContents as fetchThreadContentsRoutine, postThreadContent} from './middlewares/thread-contents/routines';
import {ThreadContentsState} from '../../definitions/portal-interfaces';
import ThreadContent from '../../models/ThreadContent';
const initialState = {
collection: [],
meta: null,
isFetching: false,
isFetched: false
};
const fetchThreadContentsHandler = () => ({
[fetchThreadContentsRoutine.REQUEST]: (state: ThreadContentsState) => ({
...state,
isFetching: true,
isFetched: false
}),
[fetchThreadContentsRoutine.SUCCESS]: (
state: ThreadContentsState,
{payload: {collection, meta}}: {payload: ThreadContentsState}) => {
const newCollection = unionBy((each: ThreadContent) => get('id', each), collection, state.collection);
const orderedCollection = sortBy('createdAt', newCollection);
return {
...state,
collection: orderedCollection,
meta,
isFetching: false,
isFetched: true
};
},
[fetchThreadContentsRoutine.FAILURE]: (state: ThreadContentsState) => ({
...state,
isFetching: false,
isFetched: true
})
});
const postThreadContentHandler = () => ({
[postThreadContent.SUCCESS]: (
state: ThreadContentsState,
{ payload: threadContent }: { payload: ThreadContent }) => {
return set('collection', [...state.collection, threadContent], state);
}
});
export default createReducer(initialState, {
...fetchThreadContentsHandler(),
...postThreadContentHandler()
});