I'm having a hard time pre-loading state with React / Redux.
Before marking this as duplicate, I've already read these:
Here's my scenario:
User object from the database. I need this User object to be in the state without a roundtrip to the server.User object is dynamic, I can't have it in the bundle.My problem:
How do I initially load the User object from the server into my store in the Client?
In this answer, Dan Abramov says:
On the client, you’d read it from a global variable, and create the client store instance with it. In other words you never have to manually create initialState—you’re supposed to grab it on the server with store.getState(), pass it to client, and create a store with it.
So, I'm assuming that, by global variable, he means something like this:
// Here, window._initialState.user is being sent to the client in a <script/> tag.
const store = createStore(reducers, { user: window._initialState.user);
The above might work, the problem is that I don't have confidence that this is actually a good practice because I didn't find any example on the internet about it.
So, Is this the right thing to do? Is there a better / more recommended way of doing it?
This is taken directly from the redux recipes page:
To pass along the state, we add a tag that will attach preloadedState to
window.__PRELOADED_STATE__.
function renderFullPage(html, preloadedState) {
return `
<!doctype html>
<html>
<head>
<title>Redux Universal Example</title>
</head>
<body>
<div id="root">${html}</div>
<script>
// WARNING: See the following for security issues around embedding JSON in HTML:
// http://redux.js.org/docs/recipes/ServerRendering.html#security-considerations
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
</script>
<script src="/static/bundle.js"></script>
</body>
</html>
`
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With