Redux-toolkit: createAsyncThunk TS Return Type Issue

Created on 6 May 2020  路  2Comments  路  Source: reduxjs/redux-toolkit

HI,

I followed the docs and tried implementing createAsyncThunk but its not working with Typescript as expected.

I have the below code

  • "@reduxjs/toolkit": "^1.3.5",
  • "typescript": "^3.8.3"

type.ts

export type DeleteType = {
  successList: string[],
  errorList: string[]
}

slice.ts

export const deleteTemplates = createAsyncThunk<DeleteType, string[]>('TEMPLATES/DELETE', ( async (templateIds: string[], thunkAPI) => {
    const { dispatch } = thunkAPI
    dispatch(deleteTemplatesStart())

    const { errorList, successList } = await deleteTemplatesById(templateIds)

    dispatch(deleteCompleted())

    return { errorList, successList }
  }
))

component.ts

  const onDelete = async (templateIds: string[]) => {
    const resultAction = await dispatch(deleteTemplates(templateIds))

    const data = unwrapResult(resultAction)
    console.log(data)
  }

But I get this error on the object resultAction

image

How to access my errorList, successList objects in the component

Whereas on runtime, I am getting the value inside payload but Types are causing TS error
image

Most helpful comment

@phryneas Super thanks for this. It fixed the issue
For other folks who arrived at this post, here is what I did to fix

store.ts
export type AppDispatch = typeof store.dispatch

component.ts
const dispatch: AppDispatch = useDispatch()

This will make sure that the dispatch is not the generic redux-dispatch but the one with which the store is configured (basically one which understands thunk)

All 2 comments

Your Dispatch type is not typed correctly, so the return type of useDispatch is incorrect. See
https://react-redux.js.org/using-react-redux/static-typing#typing-the-usedispatch-hook .

@phryneas Super thanks for this. It fixed the issue
For other folks who arrived at this post, here is what I did to fix

store.ts
export type AppDispatch = typeof store.dispatch

component.ts
const dispatch: AppDispatch = useDispatch()

This will make sure that the dispatch is not the generic redux-dispatch but the one with which the store is configured (basically one which understands thunk)

Was this page helpful?
0 / 5 - 0 ratings