React AJAX
Data for React components can be fetched using Ajax in the componentDidMount method. When data is retrieved from the server, it can be stored in the state and the UI can be re-rendered using the this.setState method.
When loading data asynchronously, use componentWillUnmount to cancel any unfinished requests before the component unmounts.
The following example demonstrates fetching the latest gist shared description of a Github user:
React Example
class UserGist extends React.Component {
constructor(props) {
super(props);
this.state = {username: '', lastGistUrl: ''};
}
componentDidMount() {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
}
componentWillUnmount() {
this.serverRequest.abort();
}
render() {
return (
<div>
Latest Gist shared by {this.state.username}:
<a href={this.state.lastGistUrl}>{this.state.lastGistUrl}</a>
</div>
);
}
}
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
document.getElementById('example')
);
The above code uses jQuery to complete the Ajax request.