Created
February 8, 2015 22:35
-
-
Save nicolashery/58bfeecabbb9de21efd3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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