Property 'then' does not exist on type 'AsyncThunkAction' Redux-toolkit

旧城冷巷雨未停 提交于 2021-01-28 19:07:20

问题


I can't seem to receive a Promise from createAsyncThunk function from Redux-toolkit I'm fairly new to Typescript and I'm struggling to figure out why it's giving me Property 'then' does not exist on type 'AsyncThunkAction<Student, number, {}>' error even though the promise does get returned if I remove the typing. Here is my createAsyncThunk f-n

export const getStudentByIdRequest = createAsyncThunk<Student, number>(
  'student/getStudentByIdRequest',
  async (id, { rejectWithValue }) => {
    try {
      const { data } = await instance.get(`student/${id}/`)
      return data
    } catch (err) {
      let error: AxiosError = err
      if (error) {
        return rejectWithValue({
          message: `Error. Error code ${error.response?.status}`,
        })
      }
      throw err
    }
  }
)

And that is how I dispatch it from my React component

dispatch(getStudentByIdRequest(userId)).then((res) => console.log(res))

The error appears where I try to call then on the thunk


回答1:


Your dispatch does not take types for thunks into account and thus the return type is typed incorrectly. Please use the actual Dispatch type from the store as decsribed in the documentation:

import { configureStore } from '@reduxjs/toolkit'
import { useDispatch } from 'react-redux'
import rootReducer from './rootReducer'

const store = configureStore({
  reducer: rootReducer
})

export type AppDispatch = typeof store.dispatch
export const useAppDispatch = () => useDispatch<AppDispatch>() // Export a hook that can be reused to resolve types

and then use useAppDispatch instead of useDispatch in your component.



来源:https://stackoverflow.com/questions/63811401/property-then-does-not-exist-on-type-asyncthunkaction-redux-toolkit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!