spee.ch/server/render/src/handleShowRender.jsx

74 lines
2.2 KiB
React
Raw Normal View History

import React from 'react';
import { renderToString } from 'react-dom/server';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { StaticRouter } from 'react-router-dom';
2018-04-18 21:11:25 +02:00
import renderFullPage from '../renderFullPage';
import createSagaMiddleware from 'redux-saga';
import { call } from 'redux-saga/effects';
2018-05-23 10:18:50 +02:00
import Reducers from 'client/build/reducers';
import GAListener from 'client/build/components/GAListener';
import App from 'client/build/app.js';
import Sagas from 'client/build/sagas';
import Actions from 'client/build/actions';
import Helmet from 'react-helmet';
2018-04-18 21:01:26 +02:00
const siteConfig = require('../../../config/siteConfig.js');
const returnSagaWithParams = (saga, params) => {
return function * () {
yield call(saga, params);
};
};
module.exports = (req, res) => {
let context = {};
// configure the reducers by passing initial state configs
const MyReducers = Reducers(siteConfig);
2018-05-13 20:47:57 +02:00
const MyApp = App;
const MyGAListener = GAListener(siteConfig);
// create and apply middleware
const sagaMiddleware = createSagaMiddleware();
const middleware = applyMiddleware(sagaMiddleware);
// create a new Redux store instance
const store = createStore(MyReducers, middleware);
// create saga
2018-03-31 09:20:27 +02:00
const action = Actions.onHandleShowPageUri(req.params);
const saga = returnSagaWithParams(Sagas.handleShowPageUri, action);
// run the saga middleware
sagaMiddleware
.run(saga)
.done
.then(() => {
// render component to a string
const html = renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={context}>
<MyGAListener>
<MyApp />
</MyGAListener>
</StaticRouter>
</Provider>
);
// get head tags from helmet
const helmet = Helmet.renderStatic();
// check for a redirect
if (context.url) {
return res.redirect(301, context.url);
}
// get the initial state from our Redux store
const preloadedState = store.getState();
// send the rendered page back to the client
res.send(renderFullPage(helmet, html, preloadedState));
});
};