How to access current state on Redux Toolkit on createAsyncThunk

Viewed 1044

So i want access current state of my state on state.formLogin to store in variable userCredentials how can i can access my state on createAsyncThunk?

export const loginAsync = createAsyncThunk(
  "user/login",
  async () => {
    try {
      const { content } = await login(userCredentials);
      localStorageHelpers.setUserToken(content.token);
      localStorageHelpers.setUserId(content.userId);
      return content.userId;
    } catch (err) {
      console.log(err)
    }
  }
);
1 Answers

You can access the whole state by calling thunkAPI.getState(). See PayloadCreator

export const loginAsync = createAsyncThunk(
  "user/login",
  async (_, thunkAPI) => {
    try {
      // const state = thunkAPI.getState();
      const { content } = await login(userCredentials);
      localStorageHelpers.setUserToken(content.token);
      localStorageHelpers.setUserId(content.userId);
      return content.userId;
    } catch (err) {
      console.log(err)
    }
  }
);
Related