Can I access state inside a createAsyncThunk w/axios with redux toolkit?

The async function consumes a “payload” argument, and secondly a thunkAPI object that contains a getState method.

payloadCreator

thunkAPI: an object containing all of the parameters that are normally
passed to a Redux thunk function, as well as additional options:

  • dispatch: the Redux store dispatch method
  • getState: the Redux store getState method
  • extra: the “extra argument” given to the thunk middleware on setup, if available
  • requestId: a unique string ID value that was automatically generated to identify this request sequence
  • signal: an AbortController.signal object that may be used to see if another part of the app logic has marked this request as needing
    cancelation.
  • rejectWithValue: rejectWithValue is a utility function that you can return in your action creator to return a rejected response with a
    defined payload. It will pass whatever value you give it and return it
    in the payload of the rejected action.
// AsyncThunk: getUserDetails
export const getUserDetails = createAsyncThunk(
  "userDetails/getUserDetails",
  async (arg, { getState }) => { // <-- destructure getState method
    const state = getState(); // <-- invoke and access state object
    try {
      const apiUrl = process.env.REACT_APP_URL;

      var config = {
        method: "get",
        url: `${apiUrl}/claimSet?UserName=${state.loginDetails.username}&Password=${state.loginDetails.password}`,
        headers: {
          accept: "application/json",
        },
      };

      const response = await axios(config);
      const data = await response.data;
      return data;
    } catch (error) {
      console.log(error);
    }
  }
);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)