|
| 1 | +import * as React from 'react'; |
| 2 | +import { Provider } from 'react-redux'; |
| 3 | +import { renderToString } from 'react-dom/server'; |
| 4 | +import { match, RouterContext } from 'react-router'; |
| 5 | +import createMemoryHistory from 'history/lib/createMemoryHistory'; |
| 6 | +import routes from './routes'; |
| 7 | +import configureStore from './configureStore'; |
| 8 | + |
| 9 | +export default function (params: any): Promise<{ html: string }> { |
| 10 | + return new Promise<{ html: string, globals: { [key: string]: any } }>((resolve, reject) => { |
| 11 | + // Match the incoming request against the list of client-side routes |
| 12 | + match({ routes, location: params.location }, (error, redirectLocation, renderProps: any) => { |
| 13 | + if (error) { |
| 14 | + throw error; |
| 15 | + } |
| 16 | + |
| 17 | + // Build an instance of the application |
| 18 | + const store = configureStore(); |
| 19 | + const app = ( |
| 20 | + <Provider store={ store }> |
| 21 | + <RouterContext {...renderProps} /> |
| 22 | + </Provider> |
| 23 | + ); |
| 24 | + |
| 25 | + // Perform an initial render that will cause any async tasks (e.g., data access) to begin |
| 26 | + renderToString(app); |
| 27 | + |
| 28 | + // Once the tasks are done, we can perform the final render |
| 29 | + // We also send the redux store state, so the client can continue execution where the server left off |
| 30 | + params.domainTasks.then(() => { |
| 31 | + resolve({ |
| 32 | + html: renderToString(app), |
| 33 | + globals: { initialReduxState: store.getState() } |
| 34 | + }); |
| 35 | + }, reject); // Also propagate any errors back into the host application |
| 36 | + }); |
| 37 | + }); |
| 38 | +} |
0 commit comments