unistore
unistore copied to clipboard
SSR support
This might be out of the scope of the project but is it possible to do server side rendering/ rehydration with unistore?
Not out-of-scope at all! I don't know that it'd end up being in the Unistore repo, but certainly I'd love to show an example of how to do it.
Here's roughly how it looks:
function serverRender() {
const store = createStore();
let html = renderToString(<App store={store} />);
const data = store.getState();
html = html.replace(/(<body(\s.?)?>)/, '$1<script>window.DATA='+JSON.stringify(data)+'</script>');
return html;
}
function clientRender() {
const store = createStore(window.DATA);
render(<App store={store} />, document.body);
}
use devalue instead of JSON.stringify to prevent XSS
'$1<script>window.DATA='+devalue(data)+'</script>'
That is a fantastic suggestion @stereobooster.