How to call redux action after success of another action?
Asked Answered
R

1

8

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?

Rhinal answered 28/11, 2016 at 10:24 Comment(1)
Have you read the section on Async Actions in the Redux docs? That explains it pretty well.Sukey
R
12

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);
 }
}
Recite answered 28/11, 2016 at 10:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.