Search code examples
reactjsreduxredux-thunk

Redux Thunk getState() is returning all states


Just discovered that I can use the getState() to pass state values to action creators. However I am noticing that getState() is returning all the combined states rather than the one specified in the argument. What am I doing wrong, as I don't suppose this is the correct behavior?

Reducer:

import { combineReducers } from "redux";
import { reducer as reduxForm } from "redux-form";
import authReducer from "./authReducer";

export default combineReducers({
  auth: authReducer,
  form: reduxForm
});

Action creator snippet:

export const handleProviderToken = token => async (dispatch, getState) => {
  let testState = getState("auth");
  console.log(testState); 
  const res = await axios.get(`${API_URL}/api/testEndpoint`);
  dispatch({ type: FETCH_USER, payload: res.data });
};

The console.log(testState) is showing me the entire state tree object (auth and form, rather than just auth).


Solution

  • Quoting redux-thunk documentation

    The inner function receives the store methods dispatch and getState as parameters.

    and quoting from redux's documentation

    getState()  Returns the current state tree of your application. It is equal to the last value returned by the store's reducer.

    So the getState you pass thanks to redux-thunk, is actually redux's getState() function itself and thus it is the default behavior.

    To get a specific value from your state tree, you can either use one of the following

    const { auth } = getState() 
    // OR
    const testState = getState()
    const auth = testState.auth