-
Notifications
You must be signed in to change notification settings - Fork 15
/
CounterDuck.ts
81 lines (81 loc) · 2.08 KB
/
CounterDuck.ts
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
import { Duck, reduceFromPayload } from "../../src";
import { takeEvery, call, put, select } from "redux-saga/effects";
import { delay } from "redux-saga/effects";
enum TYPE {
/** 增加 */
INCREMENT,
INCREMENT_IF_ODD,
DECREMENT,
INCREMENT_ASYNC
}
export default class MyDuck extends Duck {
get quickTypes() {
return {
...super.quickTypes,
...TYPE
};
}
get reducers() {
const { types } = this;
return {
...super.reducers,
count: (state = 0, action): number => {
switch (action.type) {
case types.INCREMENT:
return state + action.step;
case types.INCREMENT_IF_ODD:
return state % 2 !== 0 ? state + action.step : state;
case types.DECREMENT:
return state - action.step;
default:
return state;
}
}
};
}
get rawSelectors() {
type State = MyDuck["State"];
return {
...super.rawSelectors,
count(state: State) {
return state.count;
}
};
}
get creators() {
const { types, step: defaultStep } = this;
return {
...super.creators,
increment: (step = defaultStep) => ({
type: types.INCREMENT,
step
}),
incrementIfOdd: (step = defaultStep) => ({
type: types.INCREMENT_IF_ODD,
step
}),
decrement: (step = defaultStep) => ({
type: types.DECREMENT,
step
}),
incrementAsync: () => ({ type: types.INCREMENT_ASYNC })
};
}
get step() {
return 1;
}
*saga() {
yield* super.saga();
const { types, selector, selectors, creators, step } = this;
yield takeEvery(types.INCREMENT_ASYNC, function*() {
yield delay(1000);
// select state of this duck
const state = selector(yield select());
// select some value of this duck
const currentNumber = selectors.count(yield select());
// use custom property in options
// use action creators
yield put(creators.increment(step));
});
}
}