Moltes
Moltes

Reputation: 157

React / Redux - How to handle multiple async calls when loading component

I'm pretty new to React / Redux, but love to play with it so far. I came accros something that actually bothers me, but I'm not even sure it's a "real" issue I should care about. Anyway, here it is.

Let's say I have a component, which is actually a form for updating a record, retrieved from a database. This record has several foreign key to different tables. (Let's say my main table is Training, which has a Format, a Type, a Place... and all those data come from another tables).

In order to be able to display all the possible values for each of the foreign key to the user, I have to request all the different tables to get the data, and display those in dropdowns.

For now, I'm doing something like :

dispatch(new CrudActions(places).getAll());
dispatch(new CrudActions(trainingFormats).getAll());
dispatch(new CrudActions(trainingTypes).getAll());

Each of these line will dispatch a redux action, and so, update a part of the state, according to the data that is retrieved. Then my component will then simply get the values from state :

function mapStateToProps(state) {
    return {
        places: state.places.list,
        trainingFormats: state.trainingFormats.list,
        trainingTypes: state.trainingTypes.list
    }
}

It's actually working, but the consequence is : each time an action finishes and updates the state, my component get re-rendered... Let's imagine my main training has 10 foreign keys : for a single page load to display the update form, my component will be rendered 10 times. Wouldn't it cause bad performances ? Is there any better way to retrieve foreign data ?

Upvotes: 2

Views: 1540

Answers (1)

Leif
Leif

Reputation: 2170

Let me rephrase that. Each of your record components has dropdowns for places, training format and training type. The dropdown options are retrieved via ajax. When you have several records, there will be a lot of requests and rerenderings.

The solution: Don't let every record component retrieve the dropdown values on its own. For each respective dropdown, they are all the same anyway. Instead load them in one of the parent components and pass them to the record components as properties, for example as availablePlaces, availableFormats, availableTypes.

Your parent component does not even have to load the available dropdown options via ajax. It can be initialized with it.

For further optimizations concerning rerendering have a look at https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate.

Facebook recommends making ajax calls in https://facebook.github.io/react/docs/react-component.html#componentdidupdate.

Upvotes: 1

Related Questions