Reputation: 1769
I am quiet new to ReactJS. Can any one suggest me which is the correct way to make an AJAX call? Currently i am using
this.serverRequest = $.get(this.props.source, function (result) {
console.log("after serverRequest");
}.bind(this));
But I saw many samples in the tutorial
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
Please suggest me which is the correct way and why?
Upvotes: 0
Views: 217
Reputation: 5205
If your component manages AJAX requests itself, componentDidMount
is the correct lifecycle method to do this. componentDidMount
is called once, and only once in the lifecycle of a component, when it is inserted into the DOM. Nevertheless, you can factor out the logic into a separate method:
componentDidMount() {
this._serverRequest();
}
_serverRequest() {
/* your AJAX code here */
}
I have put an _
in front of the method name to express its private visibility. Although there is no method visibility support in JS, a _
is a convention to mark a method as something you should not call from the outside. For a React
component, the only public API that should be exposed to consumers is a set of props
.
One important thing to keep in mind: if your component is unmounted, e.g. removed from the DOM before your Ajax request returns, you will get an Error, as you will try to setState()
on a component that's no longer there. Although there are some safety checks you can do to prevent this, it's generally a pattern that's not recommended. You should try to manage all your AJAX requests at a higher level component, that is never supposed to be removed in the application lifecycle. If you insist on having lower-level Ajax-enabled components (a smart typeahead with server-side search, for example), it's a good practice to hide them with style={{display: 'none'}}
when they are not needed, instead of removing them form the DOM. This not only avoids such Ajax-related errors, but also any unnecessary duplicate Ajax-requests (as componentDidMount
would be called every time the component is newly inserted into the DOM).
But, in a real-world application, it's usually better to keep all your business logic and all your server-side communication outside of your components. Use React
purely for rendering, and use a framework or design pattern like redux
or flux
for managing the application state.
Upvotes: 2