Skip to content

Commit 2be4ad9

Browse files
committed
Allow fetchData to be defined in container components so that pages that require remote data can be fetched before being server-rendered
1 parent 736e3f0 commit 2be4ad9

File tree

1 file changed

+34
-6
lines changed

1 file changed

+34
-6
lines changed

server/server.js

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,26 @@ function handleRender(req, res) {
3737

3838
// See react-router's Server Rendering section:
3939
// https://reacttraining.com/react-router/web/guides/server-rendering
40-
const match = routes.reduce((acc, route) => {
41-
const { path, exact } = route;
42-
return matchPath(req.url, path, { exact }) || acc || null;
43-
});
40+
const matches = routes.reduce((matches, route) => {
41+
const { path } = route;
42+
const match = matchPath(req.url, { path, exact: true, strict: false });
43+
44+
if (match) {
45+
const wc = route.component && route.component.WrappedComponent;
46+
47+
matches.push({
48+
route,
49+
match,
50+
fetchData: (wc && wc.fetchData) || (() => Promise.resolve())
51+
});
52+
53+
}
54+
55+
return matches;
56+
}, []);
4457

4558
// No matched route, render a 404 page.
46-
if (!match) {
59+
if (!matches.length) {
4760
res.status(404).send(render(<ErrorPage code={404} />, finalState));
4861
return;
4962
}
@@ -57,7 +70,22 @@ function handleRender(req, res) {
5770
</Provider>
5871
);
5972

60-
res.status(200).send(render(component, finalState));
73+
// an array of fetchData promises.
74+
const fetchData = matches.map(match => {
75+
const { fetchData, ...rest } = match; // eslint-disable-line no-unused-vars
76+
77+
// return fetch data Promise, excluding unnecessary fetchData method
78+
return match.fetchData({ store, ...rest });
79+
});
80+
81+
// Execute the render only after all promises have been resolved.
82+
Promise
83+
.all(fetchData)
84+
.then(() => {
85+
const state = store.getState();
86+
res.status(200).send(render(component, state));
87+
});
88+
6189
}
6290

6391
app.listen(port, (error) => {

0 commit comments

Comments
 (0)