alextrastero
alextrastero

Reputation: 4280

Dispatch thunk from another thunk created with createAsyncThunk from redux-toolkit

This is more typescript question, but my issue is specific inside createAsyncThunk method from @redux/toolkit. What is the return type from dispatching a thunk action?

const myService = (num: number) => Promise.resolve(num.toString());

const myAction = createAsyncThunk(
  'FOO', myService
)

const myFirstAction = createAsyncThunk<
  string, // return type
  number // param type
>('First', (num) => {
  return myService(num) // calling service directly so OK
})

const mySecondAction = createAsyncThunk<
  string, // WORKS because i'm calling unwrapResult on resolved value
  number, // param type
  {
    dispatch: AppDispatch,
  }
>('Second', (num, { dispatch }) => {
  return dispatch(myFirstAction(num)).then(unwrapResult)
})

const myThirdAction = createAsyncThunk<
  string, // FAILS ?? <- What type to use here
  number, // param type
  {
    dispatch: AppDispatch,
  }
>('Third', (num, { dispatch }) => {
  return dispatch(myFirstAction(num))
})

Upvotes: 1

Views: 1599

Answers (1)

phry
phry

Reputation: 44086

Strictly speaking, it's

ReturnType< AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> >

but, as that type is not exported,

ReturnType< AsyncThunk<
  Returned,
  ThunkArg,
  ThunkApiConfig
> >

should do the trick.

You can see the sources for this type here.

Upvotes: 1

Related Questions