-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsaga-cli-demo.js
67 lines (57 loc) · 2.16 KB
/
saga-cli-demo.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 {createStore, combineReducers, applyMiddleware} from 'redux';
import createSagaMiddleware from 'redux-saga'
import { takeEvery } from 'redux-saga'
import * as effect from 'redux-saga/effects';
import {FakeApi} from './fixture';
const INITIAL_API_STATE={pending: 0, failed: 0, fetched: {}, failures: {}};
const sagaMiddleware = createSagaMiddleware();
const store = createStore(combineReducers ({
api: (state=INITIAL_API_STATE, action) => {
switch (action.type) {
case 'started':
return Object.assign({}, state, {pending: state.pending + 1});
case 'received':
const data = action.data;
const fetched = Object.assign({},
state.fetched,
{[data.id]: data});
return Object.assign({}, state, {pending: state.pending - 1,
fetched: fetched});
case 'failed':
const failures = Object.assign({},
state.failures,
action.failure)
return Object.assign({}, state, {pending: state.pending - 1,
failed: state.failed + 1,
failures: failures});
}
return state;
},
}), applyMiddleware(sagaMiddleware));
let n = 0;
store.subscribe (() => {
const state = store.getState()
console.log(`----------------------- RENDER ${n} -----------------------\n`,
JSON.stringify(state.api, null, 2));
n++;
})
function *handleFetching(action) {
try {
store.dispatch({type: 'started', pending: action.ident})
const who = yield effect.call(FakeApi.fetch, action.ident)
store.dispatch({type: 'received', data: who})
if (who.friends.length > 0) {
for(const friend of who.friends) {
// NB: Recursive action FTW!
store.dispatch({type: 'fetch!', ident: friend})
}
}
} catch (err) {
store.dispatch({type: 'failed', failure: {[action.ident]: err.message}})
}
}
function *mySaga() {
yield *takeEvery('fetch!', handleFetching)
}
sagaMiddleware.run(mySaga);
store.dispatch({type: 'fetch!', ident: '1'})