Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call redux action after success of another action?

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?

like image 223
j_d Avatar asked Nov 28 '16 10:11

j_d


1 Answers

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);
 }
}
like image 187
Sergey Tyupaev Avatar answered Sep 22 '22 06:09

Sergey Tyupaev