Search code examples
reactjsreduxredux-thunkredux-toolkit

React-Redux: getState() not available


I've encountered this really frustrating issue with redux and getState(). I have this async thunk:

export const getUser = () => async (dispatch, getState) => {
  try {
    dispatch(requestCurrentUser());
    const user = await apiService.getUser();
    console.log(user);
    debugger;
  } catch (e) {
    dispatch(failureCurrentUser(e));
  }
};

The debugger activates, as it should, but getState() is not defined, only dispatch(). What is weird is that if I step through the call stack and land on the first line export const getUser = () => async (dispatch, getState) => {, getState is defined there but for some reason, when the function starts executing, it becomes unavailable.

If it is of any importance - I'm calling getUser() in the root file of the project, in a useEffect() like this:

  useEffect(() => {
    store.dispatch(getCurrentUser());
  }, []);

I have to call it via store since this root component renders the <Provider />.

Also, I'm using redux-toolkit and now migrating gradually from pure redux, hence the action.


Solution

  • Devtools will remove unused variables from scope, when you run the below code in console and at the debugger breakpoint try to access value you'll get Uncaught ReferenceError: value is not defined error.

    function test (value){
      console.log('value is fine here:',value);
      return function something(){
       //here try to console log value in the console
       debugger;
       return 88
      }
    }
    test(22)()
    

    So in your code you can just use getState and it will not be removed after optimization:

    export const getUser = () => async (dispatch, getState) => {
      try {
        //using getState here so it won't be removed from scope
        console.log(getState);
        dispatch(requestCurrentUser());
        const user = await apiService.getUser();
        console.log(user);
        debugger;
      } catch (e) {
        dispatch(failureCurrentUser(e));
      }
    };