Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React and Redux: Dispatching all actions within one function

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())
    
};
like image 480
tim_woods Avatar asked Nov 11 '20 16:11

tim_woods


People also ask

How do you dispatch actions in a functional component?

There are two ways to dispatch actions from functional components: Using mapDispatachToProps function with connect higher order component, same as in class based components. Using useDispatch hook provided by react-redux . If you want to use this hook, then you need to import it from the react-redux package.

Does Redux support multiple actions?

Well, no matter what you pass to dispatch , it is still a single action. Even if your action is an array of objects, or a function which can then create more action objects!

Who is responsible for dispatching the action in Redux?

A Redux app really only has one reducer function: the "root reducer" function that you will pass to createStore later on. That one root reducer function is responsible for handling all of the actions that are dispatched, and calculating what the entire new state result should be every time.

How to use Redux actions outside a React component?

But the only limitation of both the methods is that they can’t be used outside a React component else Redux will yell at you like anything. 3. Dispatching actions directly using the redux store object This store has the actual dispatch method that redux provides. So if you want to dispatch actions outside React components you can simply do that by

How to dispatch multiple actions in a single method in Redux?

If we want to dispatch many actions in a single method, we can do that as shown below: To run many async instructions one after the other and also maintain readability of the code, we can dispatch an action that will then trigger a saga. We can use redux-saga library in the same way.

How to dispatch an action from a React component?

When we want to dispatch an action from our React component, we need to first connect it with the store and use the "connect" method of react-redux, i.e., the second approach discussed above. When we start having logic in our mapDispatchToProps function, we can dispatch action in our saga, i.e., the third approach, which we discussed in detail.

How do I dispatch a message to the Redux store?

The dispatch method is available on the store object. An action gets dispatched to trigger an update to the Redux store. 1 // MessageSender.js 2 import { sendMsg } from './actions'; 3 // ... 4 this.props.store.dispatch(sendMsg(msg)) 5 // ... The downside of the above approach is that our React component is aware of the app logic.


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...

like image 51
Hend El-Sahli Avatar answered Oct 24 '22 06:10

Hend El-Sahli