What is the general practice of setting the initial state of the app with isomorphic applications? Without Flux I would simple use something like:
var props = { }; // initial state
var html = React.renderToString(MyComponent(props);
Then render that markup via express-handlebars and display via {{{reactMarkup}}
.
On the client-side to set the initial state I would do something like this:
if (typeof window !== 'undefined') {
var props = JSON.parse(document.getElementById('props').innerHTML);
React.render(MyComponent(props), document.getElementById('reactMarkup'));
}
So yes essentially you are setting the state twice, on server and client, however React will compare the differences and in most cases so it won't impact the performance by re-rendering.
How would this principle work when you have actions and stores in the Flux architecture? Inside my component I could do:
getInitialState: function() {
return AppStore.getAppState();
}
But now how do I set the initial state in the AppStore from the server? If I use React.renderToString
with no passed properties it will call AppStore.getAppState()
which won't have anything in it because I still don't understand how would I set the state in my store on the server?
I am still looking for a clean solution that does not involve using third-party Flux implementations like Fluxible, Fluxxor, Reflux.
Use Redux.
If you are willing to work with alt.js you can achieve it with alt.bootstrap
and alt.flush
(docs)
I'm using node js with react server side rendering and alt.js as my flux implementation.
This is how it looks:
var data = {}; // Get the data whatever you want and return it bootstrap ready.
// Reminder - renderToString is synchronised
var app = React.renderToString(
AppFactory(data)
);
// In this point the react rendering was finished so we can flush the data and reset the stores
alt.flush();
In my app.jsx
/**
*
*/
componentWillMount: function () {
// This beauty here is that componentWillMount is run on the server and the client so this is all we need to do. No need for other third-party isomorphic frameworks
alt.bootstrap(
JSON.stringify(this.props, null, 3)
);
}