2

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 => {

1 Comment

That's a actually a very old style of doing Redux with TypeScript and we do not recommend having individual action types any more - you should not need to write such an implementation detail by hand. See redux.js.org/introduction/why-rtk-is-redux-today for more details and redux-toolkit.js.org/tutorials/typescript for instructions how to set up the types according to the current recommendations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.