Home > Mobile >  Dispatch type for custom middleware in redux
Dispatch type for custom middleware in redux

Time:02-15

I'm using redux toolkit, and have created a thunk using createAsyncThunk that gets called from a middleware (code below). What is the correct dispatch type? Right now it only works if I specify "any".


import { Action, Dispatch } from "redux";
import { updateTerm } from "../slices/explore";

const middleWare = ({ dispatch }: { dispatch: Dispatch<Action> }) => {
  return (next: (action: Action) => void) => {
    return (action: Action) => {
      next(action);
      if (updateTerm.match(action)) {       
          dispatch<any>(getShows(action.payload)); 
      }
    };
  };
};

const getShows = createAsyncThunk<
  Show[],
  string,
  { rejectValue: SearchError }
>("explore/getShows", async (term: string, { rejectWithValue }) => {
 //do async stuff
});


CodePudding user response:

The short answer is that you would need to use the ThunkDispatch type from the redux-thunk library.

Ideally, you wouldn't reference that at all, and instead use [the AppDispatchtype inferred fromstore.dispatch](https://redux.js.org/tutorials/typescript-quick-start#define-root-state-and-dispatch-types). However, because this is a middleware, and middleware themselves alter the type of store.dispatch`, you'd end up with a circular type definition problem.

Having said that, I'd actually recommend not writing a custom middleware here, especially for just dispatching one action.

Instead, I'd recommend using the new "listener middleware" that will be out in the next version of Redux Toolkit. It's currently available as a standalone @rtk-incubator/action-listener-middleware package.

  • Related