Skip to content

Add rethrow flag to createAsyncThunk #391

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions etc/redux-toolkit.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export function createAction<P = void, T extends string = string>(type: T): Payl
export function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;

// @alpha (undocumented)
export function createAsyncThunk<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}>(type: string, payloadCreator: (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => Promise<Returned> | Returned): ((arg: ThunkArg) => (dispatch: GetDispatch<ThunkApiConfig>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => Promise<PayloadAction<Returned, string, {
export function createAsyncThunk<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}>(type: string, payloadCreator: (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => Promise<Returned> | Returned, rethrow?: boolean): (((arg: ThunkArg, rethrow?: boolean) => (dispatch: GetDispatch<ThunkApiConfig>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => Promise<PayloadAction<Returned, string, {
arg: ThunkArg;
requestId: string;
}, never> | PayloadAction<undefined, string, {
Expand All @@ -126,7 +126,30 @@ export function createAsyncThunk<Returned, ThunkArg = void, ThunkApiConfig exten
arg: ThunkArg;
requestId: string;
}>;
};
} & false) | (((arg: ThunkArg, rethrow?: boolean) => (dispatch: GetDispatch<ThunkApiConfig>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => Promise<PayloadAction<Returned, string, {
arg: ThunkArg;
requestId: string;
}, never> | PayloadAction<undefined, string, {
arg: ThunkArg;
requestId: string;
aborted: boolean;
}, any>> & {
abort: (reason?: string | undefined) => void;
}) & {
pending: ActionCreatorWithPreparedPayload<[string, ThunkArg], undefined, string, never, {
arg: ThunkArg;
requestId: string;
}>;
rejected: ActionCreatorWithPreparedPayload<[Error, string, ThunkArg], undefined, string, any, {
arg: ThunkArg;
requestId: string;
aborted: boolean;
}>;
fulfilled: ActionCreatorWithPreparedPayload<[Returned, string, ThunkArg], Returned, string, never, {
arg: ThunkArg;
requestId: string;
}>;
} & true);

// @alpha (undocumented)
export function createEntityAdapter<T>(options?: {
Expand Down
41 changes: 41 additions & 0 deletions src/createAsyncThunk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,47 @@ describe('createAsyncThunk', () => {
expect(errorAction.meta.requestId).toBe(generatedRequestId)
expect(errorAction.meta.arg).toBe(args)
})

it('accepts arguments, dispatches actions and then throws when rethrow is specified', async () => {
const dispatch = jest.fn()

let passedArg: any

const result = 42
const args = 123
let generatedRequestId = ''

let rethrowErr

const error = new Error('Panic!')

const thunkActionCreator = createAsyncThunk(
'app/fakeRequest',
async (arg: number, { requestId }) => {
passedArg = arg
generatedRequestId = requestId
throw error
},
true
)

const thunkFunction = thunkActionCreator(args, true)

try {
await thunkFunction(dispatch, () => {}, undefined)
} catch (err) {
rethrowErr = err
}

expect(rethrowErr).toBeTruthy()
expect(dispatch).toHaveBeenCalledTimes(2)

// Have to check the bits of the action separately since the error was processed
const errorAction = dispatch.mock.calls[1][0]
expect(errorAction.error).toEqual(miniSerializeError(error))
expect(errorAction.meta.requestId).toBe(generatedRequestId)
expect(errorAction.meta.arg).toBe(args)
})
})

describe('createAsyncThunk with abortController', () => {
Expand Down
27 changes: 20 additions & 7 deletions src/createAsyncThunk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<
*
* @param type
* @param payloadCreator
* @param rethrow
*
* @alpha
*/
Expand All @@ -101,7 +102,8 @@ export function createAsyncThunk<
payloadCreator: (
arg: ThunkArg,
thunkAPI: GetThunkAPI<ThunkApiConfig>
) => Promise<Returned> | Returned
) => Promise<Returned> | Returned,
rethrow?: boolean
) {
const fulfilled = createAction(
type + '/fulfilled',
Expand Down Expand Up @@ -139,13 +141,14 @@ export function createAsyncThunk<
}
)

function actionCreator(arg: ThunkArg) {
function actionCreator(arg: ThunkArg, rethrow: boolean = false) {
return (
dispatch: GetDispatch<ThunkApiConfig>,
getState: () => GetState<ThunkApiConfig>,
extra: GetExtra<ThunkApiConfig>
) => {
const requestId = nanoid()
let rethrowErr

const abortController = new AbortController()
let abortReason: string | undefined
Expand Down Expand Up @@ -179,24 +182,34 @@ export function createAsyncThunk<
])
} catch (err) {
finalAction = rejected(err, requestId, arg)
rethrowErr = err
}
// We dispatch the result action _after_ the catch, to avoid having any errors
// here get swallowed by the try/catch block,
// per https://twitter.com/dan_abramov/status/770914221638942720
// and https://redux-toolkit.js.org/tutorials/advanced-tutorial#async-error-handling-logic-in-thunks

dispatch(finalAction)

if (rethrow && rethrowErr) {
throw rethrowErr
}

return finalAction
})()
return Object.assign(promise, { abort })
}
}

return Object.assign(actionCreator, {
pending,
rejected,
fulfilled
})
return Object.assign(
actionCreator,
{
pending,
rejected,
fulfilled
},
rethrow
)
}

/**
Expand Down