Search code examples
reactjsreduxredux-toolkit

Dispatch action on the createAsyncThunk?


I hava a thunk action was created by createAsyncThunk. I want to dispatch an action before call api to update state.

I don't want use action getProducts.pending because I want dispatch actionLoading() for other thunk actions.

How I can i do it? Thanks!

export const getProducts = createAsyncThunk("getProducts", async () => {

  // I want dispatch action actionCallAPIPending like that
  // dispatch(actionLoading());
  const response = await axios.get("api");
  return response;
});

Solution

  • You can do it like this with the second param of callback function in the createAsyncThunk:

    export const getProducts = createAsyncThunk("getProducts", async (_, thunkAPI) => {
      thunkAPI.dispatch(actionLoading());
      const response = await axios.get("api");
      return response;
    });