Files
react.dev/tips/12-initial-ajax.md
Tom Haggie 599ea5e51e Updated the ajax to tip to also mention that you need to check
that the component is still mounted before updating it's state.

Closes #1600.
2014-05-26 20:29:48 -07:00

1.2 KiB

id, title, layout, permalink, prev, next
id title layout permalink prev next
initial-ajax Load Initial Data via AJAX tips initial-ajax.html dom-event-listeners.html 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().

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

/** @jsx React.DOM */

var UserGist = React.createClass({
  getInitialState: function() {
    return {
      username: '',
      lastGistUrl: ''
    };
  },

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

  render: function() {
    return (
      <div>
        {this.state.username}'s last gist is
        <a href={this.state.lastGistUrl}>here</a>.
      </div>
    );
  }
});

React.renderComponent(
  <UserGist source="https://api.github.com/users/octocat/gists" />,
  mountNode
);