@@ -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
6391app . listen ( port , ( error ) => {
0 commit comments