Created
July 30, 2017 21:11
-
-
Save maciejsikora/b201a8a791b0c457b6573c25583a5cd8 to your computer and use it in GitHub Desktop.
Universal Application in React - Server Rendering Part
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const renderPage = (req, res, store) => { | |
const reactPart = renderToString( | |
<Provider store={store}> | |
<StaticRouter | |
location={req.url} | |
context={{}}> | |
<App/> | |
</StaticRouter> | |
</Provider> | |
); | |
res.status(200).send(` | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charSet="utf-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Fat Server Universal App</title> | |
<link rel="icon" type="image/x-icon" href="/fat.ico" /> | |
</head> | |
<body> | |
<div id="app">${reactPart}</div> | |
<script> | |
window.__STATE__ = ${JSON.stringify(store.getState()).replace(/</g, '\\u003c')} | |
</script> | |
<script type="text/javascript" src="/build.js"></script> | |
<script type="text/javascript"> | |
initApp("${req.url}"); | |
</script> | |
</body> | |
</html>`); | |
}; | |
// universal routing and rendering | |
app.get('/', async (req, res) => { | |
const store = createStore(reducer.main); | |
store.dispatch(reducer.actions.SET_PAGE(reducer.pages.MAIN)); | |
await reducer.asyncActions.fetchAccounts(store.dispatch); | |
renderPage(req, res, store); | |
}); | |
app.get('/account/:id',async (req, res) => { | |
const store = createStore(reducer.main); | |
store.dispatch(reducer.actions.SET_PAGE(reducer.pages.SUB)); | |
await reducer.asyncActions.fetchAccountFields(store.dispatch); | |
await reducer.asyncActions.fetchAccount(req.params.id, store.dispatch); | |
renderPage(req, res, store); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment