You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.2 KiB

11 years ago
---
id: initial-ajax
title: Load Initial Data via AJAX
layout: tips
11 years ago
permalink: initial-ajax.html
prev: dom-event-listeners.html
next: false-in-jsx.html
11 years ago
---
Fetch data in `componentDidMount`. When the response arrives, store the data in state, triggering a render to update your UI.
11 years ago
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:
11 years ago
```js
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
11 years ago
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
});
}
11 years ago
}.bind(this));
},
11 years ago
render: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
React.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
11 years ago
);
```