0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I am confused, why we want to use jquery for the ajax call? if react itself providing the serverRequest method to call ajax!
@ShinoyBabu: React does not, by default, provide a serverRequest method on React.Component. You don't need to use jquery - you can use plain JS, you can use a polyfill for fetch, you can use whatever you chose - but you do need to write your Ajax loading logic yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.