Redux-toolkit: createAsyncThunk TS usage

Created on 26 Mar 2020  路  1Comment  路  Source: reduxjs/redux-toolkit

QUESTION

Hi,
Thank you for the new release. I have studied the docs but I am having a hard time figuring out exactly how to use createAsyncThunk.
Below is a snippet I wrote which is giving me the error:

Argument of type '(username: string, password: string) => Promise<LoginState>' is not assignable to parameter of type '(arg: string, thunkAPI: BaseThunkAPI<unknown, unknown, ThunkDispatch<unknown, unknown, AnyAction>, unknown>) => RejectWithValue<unknown> | LoginState | Promise<...>'.
  Types of parameters 'password' and 'thunkAPI' are incompatible.
    Type 'BaseThunkAPI<unknown, unknown, ThunkDispatch<unknown, unknown, AnyAction>, unknown>' is not assignable to type 'string'.

What am I doing wrong here?

const fetchUserById = createAsyncThunk(
  "login",
  async (username: string, password: string) => {
    const response = await axios
      .post<LoginState>("/api/profiles/auth/login", {
        username: username,
        password: password
      })
    return response.data;
  }
);

Most helpful comment

The second parameter is fixed as a ThunkAPI parameter that provides several helper methods. If you want to pass in multiple values, you have to do so as an object on the first argument:

const fetchUserById = createAsyncThunk(
  "login",
-  async (username: string, password: string) => {
+  async ({username, password}: {username: string, password: string}) => {
    const response = await axios
      .post<LoginState>("/api/profiles/auth/login", {
        username: username,
        password: password
      })
    return response.data;
  }
);

>All comments

The second parameter is fixed as a ThunkAPI parameter that provides several helper methods. If you want to pass in multiple values, you have to do so as an object on the first argument:

const fetchUserById = createAsyncThunk(
  "login",
-  async (username: string, password: string) => {
+  async ({username, password}: {username: string, password: string}) => {
    const response = await axios
      .post<LoginState>("/api/profiles/auth/login", {
        username: username,
        password: password
      })
    return response.data;
  }
);
Was this page helpful?
0 / 5 - 0 ratings