Skip to content

Instantly share code, notes, and snippets.

@romac
Last active August 29, 2015 13:57
Show Gist options
  • Save romac/9773556 to your computer and use it in GitHub Desktop.
Save romac/9773556 to your computer and use it in GitHub Desktop.
A simple example of how to load a React application's initial state with Rx.
'use strict';
var Rx = require('./rx');
function fetchJSON(url, data)
{
var promise = $.getJSON(url, data).promise();
return Rx.Observable.fromPromise(promise);
}
module.exports = fetchJSON;
'use strict';
var Rx = require('./rx-lite'),
React = require('react'),
Players = require('./Players'),
CurrentGames = require('./CurrentGames'),
JoinRequests = require('./JoinRequests');
var Dashboard = React.createClass({
getInitialState: function() {
return {
user: null,
currentGames: [],
joinRequests: []
};
},
componentDidMount: function() {
this.fetchInitialState().subscribe(this.setState.bind(this));
},
// TODO: Handle errors.
fetchInitialState: function() {
var p = fetchJSON('/users.json')
.and(fetchJSON('/games.json');)
.and(fetchJSON('/joinRequests.json'))
.then(function(userInfo, currentGames, joinRequests) {
return {
user: userInfo,
currentGames: currentGames,
joinRequests: joinRequests
}
});
return Rx.Observable.when(p);
},
render: function() {
return (
<div>
<UserInfo user={this.state.user} />
<Games games={this.state.currentGames} />
<JoinRequests requests={this.state.joinRequests} />
</div>
);
}
});
module.exports = MainPage;
'use strict';
var Rx = require('rx/rx');
require('rx/rx.joinpatterns');
module.exports = Rx;
@romac
Copy link
Author

romac commented Mar 25, 2014

Lines 28-33 could and should be extracted into a proper combinator (named mergeAsObject(...propsNames) perhaps?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment