0

i'm using react js and redux and did an authentication with jwt.

I have a navbar with a dropdown. This dropdown is only visible for authenticated users. The dropdown items are dynamicly and should be loaded from a server after an user logged in.

But i have no idea where i should trigger the api call to load the dropdown items. When i click on "login" an authentication action will be triggerd. In this action i do the authentication and return a boolean to a reducer. Then the state "authenticated" switched to "true" and he dropdown will be shown. Now the dropdown items should be displayed to the user.

But when i should load them?

My thinking was to put the "load dropdown items" logic into a reducer so i can wait for the "authenticated" action. But the logic should be implemented in the action, should it?

Do you have any ideas what i can do?

  • you can use redux-thunk to make the login action- when the result comes back from the server you can dispatch the loadDropdown action. – itay312 Mar 08 '18 at 10:01

2 Answers2

2

In redux once you have authenticated the user, you can use a thunk to trigger another api call to fetch the information for the user and dispatch it corresponding action for it.

You can read more about the need and use thunks here

export function  loginUser() {
  return async (dispatch, getState) => {
      let response = await login(credentials)
      //action creator to update boolean that user is logged in
      dispatch(loginSuccessful(response)) ;
      //action creator to trigger api to fetch drop down data
      dispatch(loadDropdownItems(response)); 
  }
}
  • Ok, so the function loadDropdownItems() has to implemented in the authentication action or what file is your snipped from? –  Mar 08 '18 at 10:21
  • This is just sample method. You need to import it based on where you have it defined. That depends on how you have split your store and actions in your application. – Gokul Chandrasekaran Mar 08 '18 at 11:29
0

I think you should handle this from backend when user enters his credentials. If the user is authenticated send 'true' response with dropdown items of authenticated users.

From frontend user can handle this in action using redux thunk. Redux thunk is a middleware that helps you to return function.

In componentDidMount, call this.props.actions.authAsync()

function authAction() {
  return {
    type: 'AUTH_SUCCESS'
  };
}

function authAsync() {
  return dispatch => {
    // api call
    // based on response show dropdown items
    if(response.data.authenticated){
     // return dropdown items from response
    }
    dispatch(authAction());
  };
}
Shivani
  • 350
  • 3
  • 13
  • 1
    You're mixing all kinds of things there in your backend to do this. This is not clean at all. What if some other front-end needs to load another kind of data after login? – Joris Mans Apr 04 '18 at 21:06