5 best libraries for making AJAX calls in React

10Comments

Write your comment…

This comment has received 1 appreciation.

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.

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

Write a reply...

This comment has received 1 appreciation.

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.

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

Write a reply...

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();
Write a reply...

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 !

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

Write a reply...

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

Write a reply...

Load more responses

Join a friendly and inclusive Q&A network for coders

  • 🖥Pick the technologies you like & read great content through your feed.
  • 💬Ask a question when you want to learn more about anything.
  • 🚀Share what you know & build your portfolio.
Sign up nowLearn more

loading ...