forked from funmeerkats/Awesome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asyncReducer.ts
85 lines (70 loc) · 1.92 KB
/
asyncReducer.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
82
83
84
85
interface actionObj {
type: string,
[key: string]: number | string
}
interface actionSagaObj {
type: string,
data: actionSagaDataObj
}
interface actionSagaDataObj {
async?: boolean,
count?: number
}
const asyncDataThunk = (state: number = 0, action: actionObj) => {
switch (action.type) {
case 'ASYNC_THUNK':
case 'NOT_ASYNC_THUNK': {
return action.data;
}
default: {
return state
}
}
};
const asyncDataSaga = (state = {asyncCount: 0, notAsyncCount: 0}, action: actionObj) => {
switch (action.type) {
case 'ASYNC_SAGA': {
return {
...state,
asyncCount: action.count
};
}
case 'NOT_ASYNC_SAGA': {
return {
...state,
notAsyncCount: action.count
};
}
default: {
return state
}
}
};
const setData = (state = {}, action: actionObj) => {
switch (action.type) {
case 'SET': {
return {
...state,
[action.smth]: true
};
}
default: {
return state
}
}
};
const actionCreator = (type: string, data: number = 0): actionObj => ({type, data});
const actionCreatorForSaga = (type: string, data: actionSagaDataObj = {}): actionSagaObj => ({type, data});
const createAsyncActionHelper = (data: number) => {
return (dispatch: (action: actionObj) => void) => {
setTimeout(() => {
dispatch(actionCreator('ASYNC_THUNK', data))
}, 5000);
}
};
const createNotAsyncActionHelper = (data: number) => {
return (dispatch: (action: actionObj) => void) => {
dispatch(actionCreator('NOT_ASYNC_THUNK', data))
}
};
export {asyncDataThunk, asyncDataSaga, setData, actionCreatorForSaga, actionCreator, createAsyncActionHelper, createNotAsyncActionHelper}