/
post.js
67 lines (61 loc) · 1.86 KB
/
post.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
import { takeLatest, put, call, select } from 'redux-saga/effects';
import { createAction } from 'redux-actions';
import { push, createMatchSelector } from 'connected-react-router';
import { getPost as getPostAPI } from 'api/posts';
import { getUser as getUserAPI } from 'api/users';
import { setData as setPost } from 'redux/reducers/response/post';
import { setData as setUser } from 'redux/reducers/response/user';
import {
setIdle,
setLoading,
setFailure,
} from 'redux/reducers/ui/state';
export const HANDLE_DID_MOUNT = `post/HANDLE_DID_MOUNT`;
export const CLICK_ROOT_PATH = `post/CLICK_ROOT_PATH`;
export const handleDidMount = createAction(HANDLE_DID_MOUNT);
export const clickRootPath = createAction(CLICK_ROOT_PATH);
export const sagas = {
* handleDidMount () {
try {
const matchSelector = createMatchSelector({ path: '/posts/:id' });
const match = yield select(matchSelector);
const id = parseInt(match.params.id, 10);
yield put(setLoading());
const { success, error } = yield call(getPostAPI, id);
if (success) {
yield put(setPost(success.body));
yield call(sagas.getUser, success.body.userId);
} else {
console.log(error);
yield put(setFailure());
}
} catch (err) {
console.log(err);
}
},
* getUser (id) {
try {
const { success, error } = yield call(getUserAPI, id);
if (success) {
yield put(setUser(success.body));
yield put(setIdle());
} else {
console.log(error);
yield put(setFailure());
}
} catch (err) {
console.log(err);
}
},
* clickRootPath () {
yield put(push('/'));
},
};
export const watchers = {
* handleDidMount () {
yield takeLatest(HANDLE_DID_MOUNT, sagas.handleDidMount);
},
* clickRootPath () {
yield takeLatest(CLICK_ROOT_PATH, sagas.clickRootPath);
},
};