In Below code loadData which will fetch initial pre-render data from AWS dynamodb using expressjs reactjs server side rendering logic in SSR web app,
Below code needs to be in module which loads the page like for example product or home page
const loadData = async (route,store,match,token) => {
var searchstring = route.queryparams.s;
return await store.dispatch(getActivitys(1,searchstring));
};
export default { component: connect(
mapStateToProps,
{ loggedinUser, getActivitys }
)(withStyles(styles)(discuss)),loadData};
Below code needs to be in server side starting file,
Execute all loadData functions inside given urls and wrap promises with new promises to be able to render pages all the time.Even if we get an error while loading data, we will still attempt to render page.
app.get('*', async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type,Accept, Authortization');
res.setHeader('Acces-Control-Allow-Methods','GET, POST, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader("Cache-Control", 'public, max-age=432000, s-maxage=432000'); // HTTP 1.1.
res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
res.setHeader("Expires", "86400"); // Proxies.
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type,Accept, Authortization');
res.set('Acces-Control-Allow-Methods','GET, POST, PATCH, DELETE');
const routes = matchRoutes(Routes, req.path);
// Execute all loadData functions inside given urls and wrap promises with new promises to be able to render pages all the time
// Even if we get an error while loading data, we will still attempt to render page.
//var token = localStorage.ICWPToken;
const promises = await routes
.map(async({ route, match }) => {
route.queryparams = req.query
const token = req.cookies.ICWPToken ? JSON.parse(req.cookies.ICWPToken) : null;
return route.loadData ? await route.loadData(route,store,match,token) : null;
})
.map(promise => {
if (promise) {
return new Promise((resolve, reject) => {
promise.then(resolve).catch(resolve);
});
}
return null;
});
// Wait for all the loadData functions, if they are resolved, send the rendered html to browser.
await Promise.all(promises).then(async() => {
const context = {};
const token = req.cookies.ICWPToken ? JSON.parse(req.cookies.ICWPToken) : null;
if (token && token !== null) {
await store.dispatch(loggedinUser(token));
}
const content = renderer(req, store, context);
if (context.notFound) {
res.status(404);
}
res.send(content);
});
});