Last active
August 29, 2015 14:06
-
-
Save elierotenberg/c42b8b4cb5e7301c5735 to your computer and use it in GitHub Desktop.
AsyncDependencies
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
var AsyncDependencies = require("react-asyncdependencies"); | |
var request = require("request"); | |
var TodoList = React.createClass({ | |
mixins: [AsyncDependencies.Mixin], | |
getInitialState: function() { | |
return { | |
todosIds: null, | |
}; | |
}, | |
getAsyncDependencies: function(props, context) { | |
return { | |
todosIds: function(fn) { | |
request("http://" + context.restEndpoint + "/todoLists/" + props.listId, fn); | |
}, | |
}; | |
}, | |
getAsyncChildren: function(props, asyncState, context) { | |
return _.map(asyncState.todosIds, function(todoId) { | |
return (<Todo todoItemId={todoId} />); | |
}); | |
}, | |
render: function() { | |
return (<ul> | |
{ | |
_.map(this.state.todosIds, function(todoId) { | |
return (<li><Todo todoItemId={todoId} /></li>); | |
}) | |
} | |
</ul>); | |
}; | |
}); | |
var Todo = React.createClass({ | |
mixins: [AsyncDependencies.Mixin], | |
getInitialState: function() { | |
return { | |
todoItemData: null, | |
}; | |
}, | |
getAsyncDependencies: function(props, context) { | |
return { | |
todoItemData: function(fn) { | |
request("http://" + context.restEndpoint + "/todoItems/" + props.todoItemId, fn); | |
}, | |
}; | |
}, | |
getAsyncChildren: function() { | |
return []; | |
}, | |
render: function() { | |
return ( | |
<div>{JSON.stringify(this.state.todoItemData)}</div> | |
); | |
}, | |
}); | |
// On the server : | |
app.get("/:listId", function(req, res) { | |
co(function*() { | |
var context = { | |
restEndpoint: "my-neat-rest-server.net", | |
}; | |
var asyncDeps = yield AsyncDependencies.renderDependenciesToScriptString(<TodoList listId={42} />, context, "my-custom-identifier"); | |
var html = indexTemplate.render({ asyncDeps: asyncDeps }); | |
res.end(html); | |
}); | |
}); | |
// On the client : | |
AsyncDependencies.mountAsyncComponent("my-custom-identifier", document.getElementById("app")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment