Typescript error: TS2345: Argument of type '(dispatch: Dispatch) => Promise<void>' is not assignable to parameter of type 'AnyAction'

Viewed 70

I've been struggling with this problem for a while now so I figured I'd ask some help.

This is my function:

export function fetchToken(username: String, password: String) {
  return async (dispatch: Dispatch) => {
    dispatch(fetchTokenStart());
    try {
      const response = await Axios.post("login", {
        username: username,
        password: password,
      });
      dispatch(fetchTokenSucceed(response.data));
    } catch (error) {
      const response: errorResponse = error as errorResponse;
      dispatch(fetchTokenFailure(response.response.data));
    }
  };
}

And here I try to utilize it:

onClick={() => {
  dispatch(fetchToken("username", "password"));
}}

But then, on the fetchToken I get this Typescript error:

TS2345: Argument of type '(dispatch: Dispatch) => Promise<void>' is not assignable to parameter of type 'AnyAction'.
1 Answers

Please provide the full code for your example. We are missing several pieces like the fetchTokenStart return type.

From what I understand, you are using redux and here you are getting an error because dispatch function accepts objects, usually in the format :

{
  type: string
  payload: any
}

Here you are passing an asynchronous function (returning Promise) as parameter for the dispatch function which is invalid. You can find more information here ;)

Related