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.
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
.
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, setwindow.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 whetherwindow.INITIAL_STATE
exists, too. - Additional uses of route-specific information (query parameters) can be accessed by sending those props in via
mapStateToProps
.
Mostly the same as above. Just skip the server-rendering part.
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
.
Use react-refetch.
- Just fetch data in
componentDidMount()
on a component-by-component basis. If your application is this simple, you can get away with just usingsetState()
. You could create a higher-order component that sets the state asisLoading
,hasError
, etc., during data fetching.