Skip to content
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

pass the ThunkArg to the idGenerator function #1600

Merged
merged 5 commits into from
Oct 17, 2021
Merged
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
2 changes: 1 addition & 1 deletion docs/api/createAsyncThunk.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ An object with the following optional fields:

- `condition(arg, { getState, extra } ): boolean | Promise<boolean>`: a callback that can be used to skip execution of the payload creator and all action dispatches, if desired. See [Canceling Before Execution](#canceling-before-execution) for a complete description.
- `dispatchConditionRejection`: if `condition()` returns `false`, the default behavior is that no actions will be dispatched at all. If you still want a "rejected" action to be dispatched when the thunk was canceled, set this flag to `true`.
- `idGenerator(): string`: a function to use when generating the `requestId` for the request sequence. Defaults to use [nanoid](./otherExports.mdx/#nanoid).
- `idGenerator(arg): string`: a function to use when generating the `requestId` for the request sequence. Defaults to use [nanoid](./otherExports.mdx/#nanoid), but you can implement your own ID generation logic.
- `serializeError(error: unknown) => any` to replace the internal `miniSerializeError` method with your own serialization logic.
- `getPendingMeta({ arg, requestId }, { getState, extra }): any`: a function to create an object that will be merged into the `pendingAction.meta` field.

Expand Down
6 changes: 4 additions & 2 deletions packages/toolkit/src/createAsyncThunk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ export type AsyncThunkOptions<
*
* @default `nanoid`
*/
idGenerator?: () => string
idGenerator?: (arg: ThunkArg) => string
} & IsUnknown<
GetPendingMeta<ThunkApiConfig>,
{
Expand Down Expand Up @@ -531,7 +531,9 @@ If you want to use the AbortController to react to \`abort\` events, please cons
arg: ThunkArg
): AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> {
return (dispatch, getState, extra) => {
const requestId = (options?.idGenerator ?? nanoid)()
const requestId = options?.idGenerator
? options.idGenerator(arg)
: nanoid();

const abortController = new AC()
let abortReason: string | undefined
Expand Down
20 changes: 20 additions & 0 deletions packages/toolkit/src/tests/createAsyncThunk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,26 @@ describe('idGenerator option', () => {
expect.stringContaining('fake-fandom-id')
)
})

test('idGenerator should be called with thunkArg', async () => {
const customIdGenerator = jest.fn((seed) => `fake-unique-random-id-${seed}`)
let generatedRequestId = ''
const asyncThunk = createAsyncThunk(
'test',
async (args: any, { requestId }) => {
generatedRequestId = requestId
},
{ idGenerator: customIdGenerator }
)

const thunkArg = 1
const expected = 'fake-unique-random-id-1'
const asyncThunkPromise = asyncThunk(thunkArg)(dispatch, getState, extra)

expect(customIdGenerator).toHaveBeenCalledWith(thunkArg)
expect(asyncThunkPromise.requestId).toEqual(expected)
expect((await asyncThunkPromise).meta.requestId).toEqual(expected)
})
})

test('`condition` will see state changes from a synchronously invoked asyncThunk', () => {
Expand Down
9 changes: 7 additions & 2 deletions packages/toolkit/src/tests/createAsyncThunk.typetest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -433,10 +433,15 @@ const anyAction = { type: 'foo' } as AnyAction
// @ts-expect-error
const shouldFailNumWithoutArgs = createAsyncThunk('foo', () => {}, { idGenerator: returnsNumWithoutArgs })

const returnsStrWithArgs = (foo: any) => 'foo'
const returnsStrWithNumberArg = (foo: number) => 'foo'
// prettier-ignore
// @ts-expect-error
const shouldFailStrArgs = createAsyncThunk('foo', () => {}, { idGenerator: returnsStrWithArgs })
const shouldFailWrongArgs = createAsyncThunk('foo', (arg: string) => {}, { idGenerator: returnsStrWithNumberArg })

const returnsStrWithStringArg = (foo: string) => 'foo'
const shoulducceedCorrectArgs = createAsyncThunk('foo', (arg: string) => {}, {
idGenerator: returnsStrWithStringArg,
})

const returnsStrWithoutArgs = () => 'foo'
const shouldSucceed = createAsyncThunk('foo', () => {}, {
Expand Down