Home > Back-end >  Dispatch a function with Redux and TypeScript not working
Dispatch a function with Redux and TypeScript not working

Time:07-08

I'm trying to dispatch a function using Redux and Typescript in React, but I'm getting this error:

Argument of type '(dispatch: Dispatch) => void' is not assignable to parameter of type 'AnyAction'

Function 1:

const postProducts = (origin: string) => {
   return (dispatch: Dispatch) => {
      dispatch(initProducts(origin))
   }
}

Function 2:

export const initProducts = (origin: string) => {
   return (dispatch: Dispatch) => {
      if (origin !== 'load') {
         dispatch(setToastify(errorMsg))
      }
   }
}

Function 3:

export const setToastify = (toastifyDetails: string, open = true) => {
   return {
      type: ActionType.SET_TOASTIFY,
      toastify: toastifyDetails,
      open: open
   }
}

P.S. I know nowadays I should be using Redux Toolkit, but this project is just for educational purposes.

CodePudding user response:

for each action you should have an action type defined. for setToastify:

import { ActionType } from "../action-types";

export interface SetToastifyAction {
  type: ActionType.SET_TOASTIFY;
  payload: {
    toastifyDetails: string;
    open: boolean;
  };

your setToastify should be like this:

export const setToastify = (toastifyDetails: string, open = true):SetToastifyAction => {
   return {
      type: ActionType.SET_TOASTIFY,
      toastify: toastifyDetails,
      open: open
   }
}

you might have more than one action. Define type:

export type Action =
  | SetToastifyAction
  | AnotherAction

herAction

Then use this in your reducer:

  (state: YourStateType = initialState, action: Action):  YourStateType => {

CodePudding user response:

Your dispatch functions types are not aware that you have the thunk middleware active.

Please follow the TypeScript Quick Start tutorial to see how to set up your store in a way that the types are in place correctly. You will end up with some kind of AppDispatch type to use instead of the plain Dispatch type here.

  • Related