Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions docs/tips/12-initial-ajax.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ next: false-in-jsx.html

Fetch data in `componentDidMount`. When the response arrives, store the data in state, triggering a render to update your UI.

When processing the response of an asynchronous request, be sure to check that the component is still mounted before updating its state by using `this.isMounted()`.
When fetching data asynchronously, use `componentWillUnmount` to cancel any outstanding requests before the component is unmounted.

This example fetches the desired Github user's latest gist:

Expand All @@ -23,15 +23,19 @@ var UserGist = React.createClass({
},

componentDidMount: function() {
$.get(this.props.source, function(result) {
var lastGist = result[0];
if (this.isMounted()) {
this.setState({
serverRequest: $.get(this.props.source, function(result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}
}.bind(this));
}.bind(this))
});
},

componentWillUnmount: function() {
this.state.serverRequest.abort();
},

render: function() {
Expand Down