Skip to content

Instantly share code, notes, and snippets.

@jphalip
Last active August 29, 2015 14:27
Show Gist options
  • Save jphalip/16ed71b08c493f45072c to your computer and use it in GitHub Desktop.
Save jphalip/16ed71b08c493f45072c to your computer and use it in GitHub Desktop.
// Version 1:
// MyApp first gets rendered with empty "data", then gets re-rendered with
// ajax-fetched data after the stores gets hydrated and triggers the update.
import Reflux from 'reflux';
import React from 'react'
import $ from 'jQuery'
var Actions = Reflux.createActions([
'hydrate'
]);
var Store = Reflux.createStore({
listenables: [Actions],
onHydrate: function(data) {
this.trigger(data);
}
});
var MyApp = React.createClass({
mixins: [Reflux.connect(Store, 'data')],
render: function() {
return (
<MyChildren data={this.state.data} />
)
}
});
$.get('/api/data.json', function (data) {
var myApp = <MyApp />;
Actions.hydrate(data);
React.render(myApp, document.getElementById('myapp'));
});
// Version 2:
// MyApp first gets rendered with ajax-fetched data (via the initialData prop).
// The store also gets hydrated, triggering an update (but MyApp is already
// correctly rendered by then).
import Reflux from 'reflux';
import React from 'react'
import $ from 'jQuery'
var Actions = Reflux.createActions([
'hydrate'
]);
var Store = Reflux.createStore({
listenables: [Actions],
onHydrate: function(data) {
this.trigger(data);
}
});
var MyApp = React.createClass({
mixins: [Reflux.connect(Store, 'data')],
getInitialState: function () {
return {
data: this.props.initialData // Initialize state with ajax-fetched data
}
},
render: function() {
return (
<MyChildren data={this.state.data} />
)
}
});
$.get('/api/data.json', function (data) {
var myApp = <MyApp initialData={data} />; // Pass initial data as a prop
Actions.hydrate(data);
React.render(myApp, document.getElementById('myapp'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment