17

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;
});
queeng
  • 173
  • 1
  • 1
  • 6

3 Answers3

43

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;
});
Viet
  • 12,133
  • 2
  • 15
  • 21
3

As the createStore method got deprecated I was looking for a solution to migrate an existing project to use @reduxjs/toolkit and in the same time to set up a new one.

I found @Viet's answer very useful, although to be complete I would like to mention another way of using Async Thunks just to have it in the same thread for people who end up here and might would find it useful.

You still can create an Async Thunk without createAsyncThunk, but this way you cannot rely on the extraReducers as a downside.

export const getProducts = (): AppThunk => async (dispatch) => {
  dispatch(actionLoading());

  try {
    const response = await axios.get("api");
    // return the response or store it
    return response;
  } catch (error) {
    // handle the error
    console.warn(error)
  }

  dispatch(actionLoading());
};
Gyorgy
  • 96
  • 1
  • 1
  • 6
1

in the callback of createAsyncThunk , from second parameter you can destruct the dispatch.

 export const asyncthunk = createAsyncThunk(
      "ACTION",
      async (_,{dispatch) => {
        try {
          const { data } = await axios.get("api")
          dispatch(anotherAction())
          return data;
        } catch (error) {
          throw error;
        }
      }
    );