Search code examples
reactjstypescriptreduxreact-hooksredux-thunk

How to type dispatch of an async thunk?


I am currently using reduxjs/toolkit and I am having trouble typing my hooks to return a dispatch of an async thunk. Here is my setup following https://redux-toolkit.js.org/usage/usage-with-typescript (not fully functional code):

// thunk.ts

export const callThunk: AsyncThunk<
  ResponseBody,
  void,
  {state: RootState}
> = createAsyncThunk(
  'someAsyncThunkAction',
  async (_data, {rejectWithValue}) => {
   
      const response = await someAPICall();
      if (!response.ok) {
        return rejectWithValue(`Put failed: ${response.status}`);
      } else {
        return await response.json();
      }
);

// store.ts

export const store = configureStore({reducer: rootReducer});

export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();
// hook.ts
import {callThunk} from './thunk'
import {useAppDispatch} from './store'

type HookProperties = {
  onCallThunk: () => // <--- this is the type that I haven't figured out
};
export const useHook = (): HookProperties => {
  const appDispatch = useAppDispatch();

  return {
    onCallThunk: () => appDispatch(callThunk())
  };
};

and hopefully I can call this hook in my component as follow:

import {useHook} from './hook'

const {onCallThunk} = useHook();

onCallThunk().then(/* do something here */)

What should the type of onCallThunk be in hook.ts?


Solution

  • Your best bet here would be: either the part of it you expect to be used, so something like

    type HookProperties = {
      onCallThunk: () => void // for example if you don't care about the result being used
    };
    

    or, simply: leave the : HookProperties annotation away and leave it at that. TypeScript knows the return type better than you could write it on your own and you gain nothing by manually writing that down - except for more maintenance later on when you change something.