Skip to content

Instantly share code, notes, and snippets.

@nicolashery
Created February 8, 2015 22:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicolashery/58bfeecabbb9de21efd3 to your computer and use it in GitHub Desktop.
Save nicolashery/58bfeecabbb9de21efd3 to your computer and use it in GitHub Desktop.
// Exploring using "expose React component tree as data" @swannodette
// (https://www.youtube.com/watch?v=5hGHdETNteE#t=1559)
// for routing and fetching data ("react-router-mega-demo" @ryanflorence)
// (https://github.com/rackt/react-router-mega-demo/blob/master/app/utils/fetchData.js)
var appState = {
route: '/contacts',
contacts: [],
messages: []
};
var onChangeAppState = function noop() {};
class App extends React.Component {
componentWillMount() {
onChangeAppState = this.forceUpdate;
}
render() {
if (appState.route === '/contacts') {
return <Contacts />;
}
if (appState.route === '/messages') {
return <Messages />;
}
}
}
class Contacts extends React.Component {
render() {
// ...
}
}
Contacts.fetchData = function() {
api.getContacts((err, contacts) => {
appState.contacts = contacts;
onChangeAppState();
});
};
class Messages extends React.Component {
render() {
// ...
}
}
Messages.fetchData = function() {
api.getMessages((err, messages) => {
appState.messages = messages;
onChangeAppState();
});
};
function fetchData(tree) {
var dataFetchers = walkTree(tree, (component) => component.fetchData);
dataFetchers = filter(dataFetchers, isFunction);
concurrent(dataFetchers);
}
function onBrowserRouteChange(route) {
appState.route = route;
var tree = React.renderToTree(<App />);
// Render immediately, and fetch data in the background
// required by components for this route
// (will re-render when data comes back from server)
React.renderTree(tree, document.body);
fetchData(tree);
}
router.start(onBrowserRouteChange);
// Note:
React.render = function(element, node) {
React.renderTree(React.renderToTree(element), node);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment