5 best libraries for making AJAX calls in React

I have been working with React for the last two years. One of the questions many React beginners ask: "What's the React way to fetch data from the server" or "How should I make AJAX calls in React"? To answer your question, as many developers would tell you, React is just a view library and you are free to use whatever you are comfortable with. However, this doesn't help much - especially when the JavaScript landscape is changing so rapidly. So, in this article I will try to answer this basic question and list down 5 simple libraries for making AJAX calls in React.

jQuery $.ajax

This is a quick & dirty way to make AJAX calls. In the former, official React tutorial, they use jQuery to fetch data from the server. If you are just starting out and are playing around with React, this can save you a lot of time. Many of us are already familiar with jQuery. So, it won't take a lot of time to understand and use it in React. Here is how a simple API call is made, with jQuery:

loadCommentsFromServer: function() {
      $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data}); // Notice this
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  }

P.S. Snippet is from React's former official tutorial.

It's the same old jQuery's $.ajax used inside a React component. Notice how this.setState() is called inside the success callback. This is how you update the state with data obtained from the API call.

However, jQuery is a big library with many functionalities - So, it doesn't make sense to use it just for making API calls (Unless you are already using it for a bunch of other tasks). So, what's the alternative? What should we use? The answer is fetch API.

Fetch API

Fetch is a new, simple and standardised API that aims to unify fetching across the web and replace XMLHttpRequest. It has a polyfill for older browsers and should be used in modern web apps. If you are making API calls in Node.js you should also check out node-fetch which brings fetch to Node.js.

Here is what the modified API call looks like :

loadCommentsFromServer: function() {
    fetch(this.props.url).then(function(response){
        // perform setState here
    });
}

In most modern React tutorials you will find fetch being used. To know more about fetch, check out the following links :

Superagent

Superagent is a light weight AJAX API library created for better readability and flexibility. If due to some reason, you don't want to use fetch, you should definitely check this out. Here is a snippet to demonstrate its usage :

loadCommentsFromServer: function() {
    request.get(this.props.url).end(function(err,res){
        // perform setState here
    });
}

Superagent also has a Node.js module with the same API. If you are building isomorphic apps using Node.js and React, you can bundle superagent using something like webpack and make it available on the client side. As the APIs for client and server are the same, no code change is required in order to make it work in the browser.

Axios

Axios is a promise based HTTP client for Node.js and browser. Like fetch and superagent, it can work on both client and server. It has many other useful features which you can find on their GitHub page.

Here is how you make an API call using Axios :

loadCommentsFromServer: function() {
    axios.get(this.props.url).then(function(response){
      // perform setState here
    }).catch(function(error){
      //Some error occurred
    });
}

Request

This list will be incomplete without request library which was designed with simplicity in mind. With more that 12k GitHub stars, it's also one of the most popular Node.js modules. You can find more about request module on their GitHub page.

Sample usage :

loadCommentsFromServer: function() {
    request(this.props.url, function(err, response, body){
          // perform setState here
    });
}

My Take

As fetch is the new standardised API to interact with remote resources, I would suggest using it for all your AJAX needs (not only in React, but all types of JavaScript apps).

Comments (23)

Denny Trebbin's photo

I'll add an alternative library qwest

Qwest is a simple ajax library based on promises, and that supports XmlHttpRequest2 special data like ArrayBuffer, Blob, and FormData.

qwest.get(this.props.url)
     .then(function(xhr, response) {
        // perform setState here
     });

The reason why I'm listing it here is that it supports cancellation via

const request = qwest.get( /*... */ ).then( /* won't execute */ )
request.abort();

When components unmount/unload, call abort() to avoid React spamming the console when Ajax ​Promises resolve after the component has unmounted/unloaded from the DOM.

Show all replies
Denny Trebbin's photo

node.js member. hacking web & mobile. love pixel perfect design. hate quick & dirty. conjuring in germany. kid of the 80s.

Yeah, that's right. I favor real promises over fluid apis :-)

Niccolò Brogi's photo

I wouldn't even include jQuery...

I doesn't make much sense to load jQuery just to make Ajax calls, and it looks as if the trend is not to use jQuery anymore.

If I had to include it, for sure I wouldn't put it first in the list.

Sandeep Panda's photo

Co-Founder, Hashnode

Yes, that is what I have mentioned in the jQuery section.

Dwayne Charrington's photo

How about no library at all and just use a native XMLHttpRequest instead? Fetch is alright, but it has quite a few shortcomings now and you need a polyfill to even use it across browsers. The specification is in flux and until they address the issues like cancellation and monitoring file upload progress.

var request = new XMLHttpRequest();
request.open('GET', '/api/content', true);

request.onload = function() {
    if (this.status >= 200 && this.status < 400) {
        var data = JSON.parse(this.response);
    } else {
        console.error('Response received and there was an error');
    }
};

request.onerror = function() {
    console.error('Request error');
};

request.send();
Show all replies
Dwayne Charrington's photo

Rommy, you do realise you're responding to a three year old comment, right? Many of these issues have been resolved now.

Chris Williams's photo

Great article!

I would put my vote in for the Fetch API. What I noticed when using Axios (and it is really easy to use and gets points for that) is that it didn't ever work well with unit testing. It may be a matter of using the right version, but mocking calls through axios never resolved. Fetch solved that issue. So if you have to ever test async functions like that, Fetch gets my vote. (*disclaimer, this is just from my personal experience.)

Abhishek Jain's photo

There is also issues regarding cross domain calls with axios..

Yanni Nightingale's photo

Agree, but fetch requires Promise, what is the best Promise polyfill ?

Nicolas Siver's photo

JavaScript, ActionScript

I think, https://github.com/stefanpenner/es6-promise should work for you.

Nikhil Maheshwari's photo

I disagree with your Take, Have you tried sending a post request with fetch, it just does't work. By little search you can find the issues with fetch. Nice Article Anyways, Covers Most of the APIs !

Sandeep Panda's photo

Co-Founder, Hashnode

We have been using fetch in production at Hashnode without any problem. And yes, POST requests too.

Nicholas Stephan's photo

Great list of ajax libraries!

But if you're talking about ReactJS specifically, then every one of your examples is, in facebook's own words, an anti-pattern. You're setting state in an asynchronous callback, which means the component could be unmounted by the time the callback is called.

@fibric gets it; calling out qwest's cancellable promises. I'd recommend everyone read this post on React's blog: https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html

Iván Portilla's photo

Good post, i think you forgot Got!

Wassim's photo

Can you please check this: faxios

Jalaj Sharma's photo

Nice article, I would just like to know about your take. Can you tell me why I would like to opt for fetch when we have more cleaner option as axios? I mean no offense, I am just curious to know why should i go with fetch which has comparatively less community support.

pingx's photo

I use fetch API with a tiny wrapper >_<.

https://github.com/haoxins/fetch.io

Show all replies
Tunca's photo

Nodejs enthusiast

Is there any way to do basic auth with jsonp get request, using any library except jQuery.

Jordan Brennan's photo

Backbone still has the best API imo:

loadCommentsFromServer: function() {
    comments.fetch().then(function(response) {
        // perform setState here
    });
}

It's clear what model/resource I'm fetching, no internals like the service URL showing through, and when I get a response I have the additional benefit of the Collection API ready to do things like sort/filter/group the data.