How to call redux action after success of another action?

j_d picture j_d · Nov 28, 2016 · Viewed 11.2k times · Source

So I have an auth related reducer set up like this:

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case LOAD:
      return {
        ...state,
        loading: true,
      }
    case LOAD_SUCCESS:
      return {
        ...state,
        loading: false,
        loaded: true,
        jwt: action.jwt,
      }
    case LOAD_FAIL:
      return {
        ...state,
        loading: false,
        loaded: false,
        error: true,
        errorMessage: action.error,
      }
    case LOGIN:
      return {
        ...state,
        loaded: false,
        loggingIn: true,
      }
    case LOGIN_SUCCESS:
      return {
        ...state,
        loaded: true,
        loggingIn: false,
        jwt: jwtDecode(action.result.token),
      }
    case LOGIN_FAIL:
      return {
        ...state,
        loggingIn: false,
        user: null,
        error: true,
        errorMessage: action.error,
      }
    case LOGOUT:
      return {
        ...state,
        loggingOut: true,
      }
    case LOGOUT_SUCCESS:
      return {
        ...state,
        loggingOut: false,
        user: null,
        jwt: null,
      }
    case LOGOUT_FAIL:
      return {
        ...state,
        loggingOut: false,
        error: true,
        errorMessage: action.error,
      }
    default:
      return state
  }
}

Where LOAD is the loading of previously stored (either cookie or JWT) auth, and LOGIN/LOGOUT are self-explanatory.

I need to trigger some further actions after either a successful LOAD or LOGIN.

I want to perform a GET request to get some private data about the user that is only available once logged in, and store this private data in the redux store to be used by various parts of the application. How do I do that?

Answer

Sergey Tyupaev picture Sergey Tyupaev · Nov 28, 2016

You should use async actions to accomplish that.

You have to write async action creator, which will call multiple actions.

Something like that:

function multipleAtions() {
 return (dispatch) => { 
   dispatch(load_action);
   return fetch(`http://some_request_here`)
          .then(() => dispatch(another_action);
 }
}