First , to get data using AJAX, you have several options:
Next , you need to use it somewhere in your React component. Where and how you do this will depend on your specific application and component, but as a rule, I think there are two scenarios:
- Getting the source data (for example, a list of users).
- Getting data in response to some user interaction (for example, clicking to add more users).
Source data must be obtained in the componentDidMount() life cycle method. From React Docs :
var UserGist = React.createClass({ getInitialState: function() { return { username: '', lastGistUrl: '' }; }, componentDidMount: function() { 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: function() { this.serverRequest.abort(); }, render: function() { return ( <div> {this.state.username} last gist is <a href={this.state.lastGistUrl}>here</a>. </div> ); } }); ReactDOM.render( <UserGist source="https://api.github.com/users/octocat/gists" />, mountNode );
Here they use jQuery to retrieve data. Although this works very well, it is probably not recommended to use such a large library (in terms of size) to perform such a small task.
Receiving data in response to, for example, an action can be performed as follows:
var UserGist = React.createClass({ getInitialState: function() { return { users: [] }; }, componentWillUnmount: function() { this.serverRequest && this.serverRequest.abort(); }, fetchNewUser: function () { this.serverRequest = $.get(this.props.source, function (result) { var lastGist = result[0]; var users = this.state.users users.push(lastGist.owner.login) this.setState({ users }); }.bind(this)); }, render: function() { return ( <div> {this.state.users.map(user => <div>{user}</div>)} <button onClick={this.fetchNewUser}>Get new user</button> </div> ); } }); ReactDOM.render( <UserGist source="https://api.github.com/users/octocat/gists" />, mountNode );
source share