Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React and data fetching

Data fetching with React

I often find myself puzzling over the best ways to fetch data with React based on whether the app is universal, has Redux, etc. This is an attempt to summarize it all.

Server-side rendering, Redux and React Router 3

Use redial and redux-thunk. The fetch function that decorates the route-handling component should dispatch all data-fetching actions for Redux containers nested in the route. Additional uses of route-specific information (query parameters) can be accessed by sending those props in via mapStateToProps.

Server-side rendering, Redux and React Router 4

From what I can tell, there's no agreed-upon way to do this yet. However, react-router-config is in development to address this scenario. Also, redux-first-router might be helpful. And Apollo is always a good choice.

In theory, you could:

  • Write a single data-fetching function for the route-handling component that fetches all the data for Redux containers nested in the route. It should use redux-thunk. It could be a static method or just a function detached from the component entirely.
  • On the server, provide the function with the necessary arguments: match, location, etc. Wait for all promises to resolve, set window.INITIAL_STATE and render accordingly.
  • On the client, write a higher-order component that takes that function, as well as the route-handling component, as arguments. It simply calls the data-fetching function in componentDidMount() after providing it with necessary arguments: match, location, etc. There will probably need to be a check for whether window.INITIAL_STATE exists, too.
  • Additional uses of route-specific information (query parameters) can be accessed by sending those props in via mapStateToProps.

No server-side rendering, Redux and React Router 4

Mostly the same as above. Just skip the server-rendering part.

Redux, no routing, no server-side rendering

Define a single data-fetching function for the entire application, and call it in componentDidMount() in the root component. That function probably uses redux-thunk.

React Router 4, no Redux, no server-side rendering

Use react-refetch.

No routing, no Redux

  • Just fetch data in componentDidMount() on a component-by-component basis. If your application is this simple, you can get away with just using setState(). You could create a higher-order component that sets the state as isLoading, hasError, etc., during data fetching.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment