score:18

Accepted answer

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.

score:9

Another potential solution for this could be using ThunkDispatch type instead of plain Dispatch, as plain Dispatch is not meant to be handling async stuff.

Defining reusable useAppThunkDispatch hook in store.ts:

import { Action, ThunkDispatch, configureStore } from '@reduxjs/toolkit';

export const store = configureStore({
    reducer: {
        blog: blogSlice,
    },
});

export type RootState = ReturnType<typeof store.getState>;

export type ThunkAppDispatch = ThunkDispatch<RootState, void, Action>;

export const useAppThunkDispatch = () => useDispatch<ThunkAppDispatch>();

You can then use useAppThunkDispatch hook in your app just like useAppDispatch or useDispatch hook.


Related Query

More Query from same tag