From 2a1dc07046a0684f1d5b2d4f4b162cf2cc8a794b Mon Sep 17 00:00:00 2001 From: Jim Date: Sun, 17 Jan 2016 12:08:50 -0800 Subject: [PATCH] Merge pull request #5870 from SimenB/patch-1 Remove the recommendation to use `isMounted` from beginner docs (cherry picked from commit e09dfe1e0e49110b3b3319e8500aae5bffd36301) --- docs/tips/12-initial-ajax.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/docs/tips/12-initial-ajax.md b/docs/tips/12-initial-ajax.md index a6e0e70fa6..c28835c576 100644 --- a/docs/tips/12-initial-ajax.md +++ b/docs/tips/12-initial-ajax.md @@ -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: @@ -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() {