|
| 1 | +import { Dispatch } from 'redux' |
| 2 | +import { ActionCreatorWithPayload, createAction } from './createAction' |
| 3 | + |
| 4 | +export type Await<T> = T extends { |
| 5 | + then(onfulfilled?: (value: infer U) => unknown): unknown |
| 6 | +} |
| 7 | + ? U |
| 8 | + : T |
| 9 | + |
| 10 | +export interface AsyncThunkParams< |
| 11 | + A, |
| 12 | + D extends Dispatch, |
| 13 | + S extends unknown, |
| 14 | + E extends unknown |
| 15 | +> { |
| 16 | + args: A |
| 17 | + dispatch: D |
| 18 | + getState: () => S |
| 19 | + extra: E |
| 20 | +} |
| 21 | + |
| 22 | +export type AsyncActionCreator< |
| 23 | + A, |
| 24 | + D extends Dispatch, |
| 25 | + S extends unknown, |
| 26 | + E extends unknown |
| 27 | +> = (params: AsyncThunkParams<A, D, S, E>) => any |
| 28 | + |
| 29 | +export function createAsyncThunk< |
| 30 | + ActionType extends string, |
| 31 | + PayloadCreator extends AsyncActionCreator< |
| 32 | + unknown, |
| 33 | + Dispatch, |
| 34 | + unknown, |
| 35 | + undefined |
| 36 | + > |
| 37 | +>(type: ActionType, payloadCreator: PayloadCreator) { |
| 38 | + type ActionParams = Parameters<PayloadCreator>[0]['args'] |
| 39 | + |
| 40 | + const fulfilled = createAction(type) as ActionCreatorWithPayload< |
| 41 | + { args: ActionParams; result: Await<ReturnType<PayloadCreator>> }, |
| 42 | + ActionType |
| 43 | + > |
| 44 | + |
| 45 | + const pending = createAction(type + '/pending') as ActionCreatorWithPayload< |
| 46 | + { args: ActionParams }, |
| 47 | + string |
| 48 | + > |
| 49 | + |
| 50 | + const finished = createAction(type + '/finished') as ActionCreatorWithPayload< |
| 51 | + { args: ActionParams }, |
| 52 | + string |
| 53 | + > |
| 54 | + |
| 55 | + const rejected = createAction(type + '/rejected') as ActionCreatorWithPayload< |
| 56 | + { args: ActionParams; error: Error }, |
| 57 | + string |
| 58 | + > |
| 59 | + |
| 60 | + function actionCreator(args?: ActionParams) { |
| 61 | + return async (dispatch: any, getState: any, extra: any) => { |
| 62 | + try { |
| 63 | + dispatch(pending({ args })) |
| 64 | + const result: Await<ReturnType<PayloadCreator>> = await payloadCreator({ |
| 65 | + args, |
| 66 | + dispatch, |
| 67 | + getState, |
| 68 | + extra |
| 69 | + }) |
| 70 | + // TODO How do we avoid errors in here from hitting the catch clause? |
| 71 | + return dispatch(fulfilled({ args, result })) |
| 72 | + } catch (err) { |
| 73 | + // TODO Errors aren't serializable |
| 74 | + dispatch(rejected({ args, error: err })) |
| 75 | + } finally { |
| 76 | + dispatch(finished({ args })) |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + actionCreator.pending = pending |
| 82 | + actionCreator.rejected = rejected |
| 83 | + actionCreator.fulfilled = fulfilled |
| 84 | + actionCreator.finished = finished |
| 85 | + |
| 86 | + return actionCreator |
| 87 | +} |
0 commit comments