mirror of
https://github.com/aspnet/JavaScriptServices.git
synced 2025-12-22 17:47:53 +00:00
Enable server-side prerendering in React+Redux template
This commit is contained in:
38
templates/ReactReduxSpa/ClientApp/boot-server.tsx
Normal file
38
templates/ReactReduxSpa/ClientApp/boot-server.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import * as React from 'react';
|
||||
import { Provider } from 'react-redux';
|
||||
import { renderToString } from 'react-dom/server';
|
||||
import { match, RouterContext } from 'react-router';
|
||||
import createMemoryHistory from 'history/lib/createMemoryHistory';
|
||||
import routes from './routes';
|
||||
import configureStore from './configureStore';
|
||||
|
||||
export default function (params: any): Promise<{ html: string }> {
|
||||
return new Promise<{ html: string, globals: { [key: string]: any } }>((resolve, reject) => {
|
||||
// Match the incoming request against the list of client-side routes
|
||||
match({ routes, location: params.location }, (error, redirectLocation, renderProps: any) => {
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Build an instance of the application
|
||||
const store = configureStore();
|
||||
const app = (
|
||||
<Provider store={ store }>
|
||||
<RouterContext {...renderProps} />
|
||||
</Provider>
|
||||
);
|
||||
|
||||
// Perform an initial render that will cause any async tasks (e.g., data access) to begin
|
||||
renderToString(app);
|
||||
|
||||
// Once the tasks are done, we can perform the final render
|
||||
// We also send the redux store state, so the client can continue execution where the server left off
|
||||
params.domainTasks.then(() => {
|
||||
resolve({
|
||||
html: renderToString(app),
|
||||
globals: { initialReduxState: store.getState() }
|
||||
});
|
||||
}, reject); // Also propagate any errors back into the host application
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user