-
Notifications
You must be signed in to change notification settings - Fork 11
/
posts.js
113 lines (102 loc) · 2.45 KB
/
posts.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
113
import { combineReducers } from 'redux';
import {
FETCH_POSTS_START,
FETCH_POSTS_SUCCESS,
FETCH_POSTS_FAILURE,
AUTH_REQUEST_SUCCESS,
LIKE_POST,
UNLIKE_POST,
} from '~/redux/actions/actionTypes';
const initialState = {
allIds: [],
byId: {},
isFetching: false,
pagination: {},
};
const allIds = (state = initialState.allIds, action) => {
switch (action.type) {
case AUTH_REQUEST_SUCCESS:
return action.payload.posts.map(post => post.id);
case FETCH_POSTS_SUCCESS:
return action.payload.reduce((nextState, post) => {
if (nextState.indexOf(post.id) === -1) {
nextState.push(post.id);
}
return nextState;
}, [...state])
default:
return state;
}
}
const post = (state = {}, action) => {
switch (action.type) {
case LIKE_POST:
return {
...state,
likesCount: state.likesCount + 1,
}
case UNLIKE_POST:
return {
...state,
likesCount: state.likesCount - 1,
}
default:
return state;
}
}
const byId = (state = initialState.byId, action) => {
switch (action.type) {
case AUTH_REQUEST_SUCCESS:
return action.payload.posts.reduce((nextState, post) => {
nextState[post.id] = post;
return nextState;
}, {});
case FETCH_POSTS_SUCCESS:
return action.payload.reduce((nextState, post) => {
nextState[post.id] = post;
return nextState;
}, {...state})
case LIKE_POST:
case UNLIKE_POST:
return {
...state,
[action.id]: post(state[action.id], action)
}
default:
return state;
}
}
const isFetching = (state = initialState.isFetching, action) => {
switch (action.type) {
case FETCH_POSTS_START:
return true;
case FETCH_POSTS_SUCCESS:
case FETCH_POSTS_FAILURE:
return false;
default:
return state;
}
}
const pagination = (state = initialState.pagination, action) => {
switch (action.type) {
case FETCH_POSTS_SUCCESS:
return action.pagination;
default:
return state;
}
}
export default combineReducers({
allIds,
byId,
isFetching,
pagination,
});
export const getPostByIds = (state, ids = []) => {
return ids.map(id => state.byId[id]);
}
export const getAllPosts = (state) => {
const { allIds, byId } = state;
return allIds.map(id => byId[id]);
}
export const getPagination = (state) => state.pagination;
export const getIsFetching = (state) => state.isFetching;