简体   繁体   中英

What is the best practice for getting initial data for a react/redux application?

Let's say that I have an application with:

  1. User that can login/logout;
  2. Any other not related to used data. For example, a list of cities.

In a server html rendering application I fetch cities from a db and then form html page with select field with these cities. In React I have a choose:

  1. Fetching cities in the componentWillMount method or
  2. Because these cities cannot be changed and most probable will be used on other pages, put the list to the redux store.

In my opinion, I have to implement some API method that returns all initial data, but it looks dirty for me.

So, question - what is the best practice for this described case?

For best performance, you should only fetch data when you need it, otherwise it eats up memory and bandwidth. If you're sure the user will always need the list, then it's OK to preload it. There's no need to return all the initial data in a single API method - you could have a section during your app bootstrap that fires off a bunch of API calls, waits for all the results, and then creates the redux store using those initial values.

The problem with waiting for the calls to finish is that your app doesn't start up until they're all done, so that's a significant performance hit depending on data size. Might well be neater to start with an empty redux store, but fire off a bunch of requests on bootstrap that will dispatch actions when they return. Eg

function bootstrap() {
   const store = createStore();
   fetchCities().then( cities => store.dispatch({
       type: "UPDATE_CITIES",
       cities
   });
   fetchCountries().then( countries => store.dispatch({
       type: "UPDATE_COUNTRIES",
       countries 
   });

   ReactDOM.render(<Provider store={ store }><MyApp /></Provider>);
}

This lets you trigger the data load, but your app can start to render while waiting for the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM