forked from jeffbski/redux-logic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogic.js
62 lines (53 loc) · 1.7 KB
/
logic.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
import Rx from 'rxjs';
import { createLogic } from 'redux-logic';
import { TIMER_START, TIMER_CANCEL, TIMER_RESET, TIMER_END,
TIMER_DECREMENT, timerEnd, timerDecrement,
timerStartError } from './actions';
import { selectors as timerSel } from './reducer';
export const timerStartLogic = createLogic({
type: TIMER_START,
cancelType: [TIMER_CANCEL, TIMER_RESET, TIMER_END], // any will cancel
// check to see if it is valid to start, > 0
validate({ getState, action }, allow, reject) {
const state = getState();
if (timerSel.status(state) === 'started') {
// already started just silently reject
return reject();
}
if (timerSel.value(state) > 0) {
allow(action);
} else {
reject(timerStartError(new Error('Can\'t start, already zero. Reset first')));
}
},
process(deps, dispatch) {
const ob$ = Rx.Observable.interval(1000)
.map(() => timerDecrement()); // send timerDecrement actions
dispatch(ob$);
}
});
const timerDecrementLogic = createLogic({
type: TIMER_DECREMENT,
validate({ getState, action }, allow, reject) {
const state = getState();
if (timerSel.value(state) > 0) {
allow(action);
} else { // shouldn't get here, but if does end
reject(timerEnd());
}
},
process({ getState }, dispatch) {
// unless other middleware/logic introduces async behavior, the
// state will have been updated by the reducers before process runs
const state = getState();
if (timerSel.value(state) === 0) {
dispatch(timerEnd());
} else { // not zero
dispatch(); // ends process logic, nothing is dispatched
}
}
});
export default [
timerStartLogic,
timerDecrementLogic
];