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
}
}
PS I know nowadays I should be using Redux Toolkit, but this project is just for educational purposes.
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.
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 => {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.