简体   繁体   中英

How to fetch data in redux before first render and set it to default state

I have dropdown filter to show items by date, for example and show data for last 24 hours, show data for last 3 days.

I have defaultState in my reducer

const defaultState = {
  dataArray: [],
  a: true,
  b: false
}

By default dataArray is empty. And I have reducer and action. In componentDidMount method I fetch data from server by dispatching some actions. If I refresh page, default page that list last items for 24 hours is empty because dataArry comes from defaultState in my reducer. But if I change page to list data for last 3 days then componentWillReceiveProps works and inside this method I fetch data and it reduce my state and returns new one with

dataArray = [{some data}]

How to fetch data and set it to state to render it after page was refreshed?

Add to defaultState a 'loading' variable and initialize it to true. When fetching of data is completed, set it to false.

In your component check this variable. If it is true display a spinner and/or a loading message, otherwise display the data.

In addition to that, every time you start fetching, before fetching, fire an action called 'FETCH_START' which will set the loading variable to true.

If there is an error in fetching, you can set another state variable to the error message. This variable will be initialized (every time you start fetching) to an empty string. If loading is completed you can check this error variable, and display the error message if there was an error, instead of displaying the data.

This process is useful for various cases, such as authentication, etc.

Yossi's answer is pretty spot on. I just want to take it a step further and mention that you can also enhance your users' experience by knowning when to fetch data. For instance, if you're on a landing page and know most of your users are going to be browsing your store, start fetching that data on the landing page while nothing is happening.

To go along with that, take a look at this: Google Dev's requestIdleCallback()

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