React and Redux: Dispatching all actions within one function

Viewed 105

In my react application, a user logs in and then directed to his/her dashboard upon authentication. In order to display all the data of the user in the dashboard I have a separate file in which there is a function called getUserData() which dispatches all the actions of the dashboard components and then getUserData() is called within loadUser() so every time the app renders it excutes loadUser(). Is this a good practice and an efficient way to display user data as the app grows larger? Or is there a better way to do it and if so, I would love to know about it. Thank you.

//App.js

const token = localStorage.getItem('token')
store.dispatch({type: USER_LOADING});
if(token){
    store.dispatch({type: USER_AUTHENTICATED})
}

class App extends Component{
  componentDidMount(){
    store.dispatch(loadUser());
  }
  render(){
  return(
  <Provider store={store}>
  <div className="App">
    <Router>
      <Switch>
        <Route exact path="/login" component={LoginPage}/>
        <ProtectedRoute exact path="/dashboard" component={Dashboard}/>
       
      </Switch>
    </Router>
  </div>
  </Provider>

);
}
};

export default App;

//Load user

export const loadUser = () => (dispatch, getState) =>{

//dispatch(getNetworkList(config))
  axios.get('/api/user/', setAuthorizationHeader(getState))
    .then(res => {
      dispatch({
      type: USER_LOADED,
      payload: res.data
    })
    dispatch(getUserData())
  })
    .catch(err => {
      dispatch(returnErrors(err.response.data, err.response.status));
      dispatch({
        type: AUTH_ERROR
      });
    });
  };

//Get user data

export const getUserData = () =>(dispatch) =>{
        dispatch(userProfile())
        dispatch(getComments())
        dispatch(getInvites())
        dispatch(getNotifications())
        dispatch(getMessages())
        dispatch(getProjects())
        dispatch(getConnections())
        dispatch(getReply())
        dispatch(getPendingRequests())
        dispatch(getAssignedTasks())
    
};
1 Answers

I'd suggest ou apply what's called Lazy Loading ... so if the userProfile is the active-tab upon loading the dashboard, you dispatch userProfile action only ... and fire the rest of the action onRelatedTabMounted

Cause most likely, the user is gonna target specific information (comments, invites, ...) ... So there'd be no need to fetch them all on-dashboard-load...

Related