From 97eb0f1a6c78a862651f07ab01913780a4ced672 Mon Sep 17 00:00:00 2001 From: Cheng Lou Date: Sun, 6 Oct 2013 22:10:18 -0400 Subject: [PATCH] ajax ex --- cookbook/cb-12-initial-ajax tip.md | 44 +++++++++++++++++++++++++++ cookbook/cb-12-initial-ajax.md | 48 ++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 cookbook/cb-12-initial-ajax tip.md create mode 100644 cookbook/cb-12-initial-ajax.md diff --git a/cookbook/cb-12-initial-ajax tip.md b/cookbook/cb-12-initial-ajax tip.md new file mode 100644 index 00000000..555e7b9f --- /dev/null +++ b/cookbook/cb-12-initial-ajax tip.md @@ -0,0 +1,44 @@ +--- +id: initial-ajax-tip +title: Load initial data via AJAX +layout: docs +permalink: initial-ajax-tip.html +--- + +Fetch data in `componentDidMount`. When they arrive, put them inside your state then render them. + +This example fetches the desired Github user's lastest gist: + +```js +/** @jsx React.DOM */ + +var UserGist = React.createClass({ + getInitialState: function() { + return { + username: '', + lastGistUrl: '' + }; + }, + componentDidMount: function() { + $.get(this.props.source, function(result) { + var lastGist = result[0]; + this.setState({ + username: lastGist.user.login, + lastGistUrl: lastGist.html_url + }); + }.bind(this)); + }, + render: function() { + return ( +
+ {this.state.username}'s last gist is + here. +
+ ); + } +}); + +React.renderComponent( + , mountNode +); +``` diff --git a/cookbook/cb-12-initial-ajax.md b/cookbook/cb-12-initial-ajax.md new file mode 100644 index 00000000..3e10a1ca --- /dev/null +++ b/cookbook/cb-12-initial-ajax.md @@ -0,0 +1,48 @@ +--- +id: initial-ajax +title: Load initial data via AJAX +layout: docs +permalink: initial-ajax.html +--- + +### Problem +You want to load initial ajax data. + +### Solution +Fetch data in `componentDidMount`. When they arrive, put them inside your state then render them. + +This example fetches the desired Github user's lastest gist: + +```js +/** @jsx React.DOM */ + +var UserGist = React.createClass({ + getInitialState: function() { + return { + username: '', + lastGistUrl: '' + }; + }, + componentDidMount: function() { + $.get(this.props.source, function(result) { + var lastGist = result[0]; + this.setState({ + username: lastGist.user.login, + lastGistUrl: lastGist.html_url + }); + }.bind(this)); + }, + render: function() { + return ( +
+ {this.state.username}'s last gist is + here. +
+ ); + } +}); + +React.renderComponent( + , mountNode +); +```