How do I resolve 'Property 'type' is missing in type 'AsyncThunkAction' using Redux Toolkit (with TypeScript)?
Asked Answered
S

3

16

I'm using Redux Toolkit with the thunk/slice below. Rather than set the errors in state, I figure I could just handle them locally by waiting for the thunk promise to resolve, using the example provided here.

I guess I could avoid doing this, and perhaps I should, by setting an error in the state but I sort of want to understand where I went wrong on this.

Argument of type 'AsyncThunkAction<LoginResponse, LoginFormData, {}>' is not assignable to parameter of type 'Action<unknown>'.
  Property 'type' is missing in type 'AsyncThunkAction<LoginResponse, LoginFormData, {}>' but required in type 'Action<unknown>'

The error arises when passing resultAction to match:

enter image description here

const onSubmit = async (data: LoginFormData) => {
  const resultAction =  await dispatch(performLocalLogin(data));
  if (performLocalLogin.fulfilled.match(resultAction)) {
    unwrapResult(resultAction)
  } else {
    // resultAction.payload is not available either
  }
};

thunk:

export const performLocalLogin = createAsyncThunk(
  'auth/performLocalLogin',
  async (
    data: LoginFormData,
    { dispatch, requestId, getState, rejectWithValue, signal, extra }
  ) => {
    try {
      const res = await api.auth.login(data);
      const { token, rememberMe } = res;
      dispatch(fetchUser(token, rememberMe));
      return res;
    } catch (err) {
      const error: AxiosError<ApiErrorResponse> = err;
      if (!error || !error.response) {
        throw err;
      }
      return rejectWithValue(error.response.data);
    }
  }
);

slice:

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: { /* ... */ },
  extraReducers: builder => {
    builder.addCase(performLocalLogin.pending, (state, action) => startLoading(state));
    builder.addCase(performLocalLogin.rejected, (state, action) => {
      //...
    });
    builder.addCase(performLocalLogin.fulfilled, (state, action) => {
      if (action.payload) {
        state.rememberMe = action.payload.rememberMe;
        state.token = action.payload.token;
      }
    });
  }
})

Thank you for any help!

Steiermark answered 6/6, 2020 at 21:40 Comment(0)
D
42

Pretty sure that you're using the standard built-in Dispatch type there, which doesn't know anything about thunks.

Per the Redux and RTK docs, you'll need to define a more specific AppDispatch type that correctly knows about thunks and declare that dispatch here is that type, like:

    // store.ts
    export type AppDispatch = typeof store.dispatch;

    // MyComponent.ts
    const dispatch : AppDispatch = useDispatch();

    const onSubmit = async () => {
        // now dispatch should recognize what the thunk actually returns
    }
Darsie answered 6/6, 2020 at 21:57 Comment(6)
Yep, that was it. Thanks!Steiermark
This solved my problem too, although it had to do with .then not being available on dispatch. I've read RTK and Redux docs a lot, and I've missed this every time!Pronty
This is a frequently-cited issue, so we clearly need to update the docs to highlight it further.Darsie
I still saw the type error after declaring dispatch as AppDispatch because I used the spread operator to define the store's middleware option. As documented, using getDefaultMiddleware().concat(...) instead fixed it.Lozar
@Darsie FWIW, the comments were pretty clear for me. I just happened to miss it in that case and didn't recognize it.Steiermark
@Darsie thanks a lot. Not sure why creating a custom hook doesn't work here. The docs should definitely be updated.Alceste
C
4

I had to add middleware: [thunk as ThunkMiddleware] to my configureStore() to get the correct types for createAsyncThunk()

Chartulary answered 29/8, 2021 at 13:43 Comment(0)
R
-1

If none of the other answers help, one thing that ended up working for me was:

  1. Delete the node_modules folder.
  2. Delete yarn.lock/package-lock.json.
  3. Run yarn install/npm install.

If you ensure you have everything else looking absolutely correct with the rest of your code like I did, then this should fix it up for you.

Radioactivate answered 11/3, 2022 at 11:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.