35

How should I handle ajax requests in a fairly traditional web application? Specifically with using React for views, while having a backend that handles data such as text and what not, but using ajax to automatically save user interactions such as toggling options or liking a post to the server.

Should I just use jQuery for this, or would something like Backbone be more beneficial?

3
  • 1
    Take a look at flux and how people are handling AJAX there: stackoverflow.com/questions/26632415/… Commented May 1, 2015 at 17:11
  • You can use either. It's up to you. If you already have some Backbone stuff in place, you could keep using it. Commented May 1, 2015 at 17:12
  • I use jQuery to make AJAX call's using React with a Django Backend. Commented May 1, 2015 at 18:29

5 Answers 5

46

Just in case anybody stumbled upon this and does not know, jQuery makes it super easy to send AJAX calls. Since React is just JavaScript it will work just like any other jQuery AJAX call.

React's own documentation uses jQuery to make the AJAX call so I assume that's good enough for most purposes regardless or stack.

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)
    });
  },
5
  • 15
    It's a huge library to pull in just for an AJAX wrapper though. The compressed version of 2.x they have up for download is 82 KB. That's a lot for a wrapper that can probably be written in few enough codelines to fit on the screen.
    – ivarni
    Commented May 1, 2015 at 20:15
  • 3
    Yeah you're right about that, but there is still so much I use jQuery for, besides just the Ajax call. It's a pain to download it with React, but jQuery is still too helpful for me to get rid of entirely. Commented May 2, 2015 at 2:34
  • 2
    On the topic of jquery being huge: alternatives include superagent and reqwest. Both have very similar APIs but superagent is only 10kB by comparison.
    – thom_nic
    Commented Sep 8, 2015 at 17:57
  • 3
    you can just add the ajax part of jQuery: stackoverflow.com/questions/4132163/…
    – gtournie
    Commented Dec 11, 2015 at 7:05
  • 3
    I got $ is not defined Commented Aug 10, 2016 at 20:28
18

Kindly checkout the official documentation of Facebook about Complementary Tools at https://github.com/facebook/react/wiki/Complementary-Tools

They simply recommends few data fetching API's like

  • axios: Promise based HTTP client for the browser and node.js.
  • jQuery AJAX: No introduction needed.
  • superagent: A lightweight "isomorphic" library for AJAX requests.
  • reqwest: AJAX all over again. Includes support for xmlHttpRequest, JSONP, CORS, and CommonJS Promises A. Browser support stretches back to IE6.

My personal favorite would be axios due to promises which works in browser as well as in nodejs env and even officially reactJS website recommend the same at AJAX and APIs

1
  • Using react-ajax is ridiculous, I can not find it out, I prefer to use fetch and use async/await for better understanding and fluent coding.
    – AmerllicA
    Commented Dec 26, 2017 at 17:41
13

You can use JavaScript Fetch API, it supports GET and POST as well, plus it has building Promises.

fetch('/api/getSomething').then(function() {...})
5
  • 2
    How do you handle cancelling an in-flight request? Commented Mar 27, 2016 at 10:28
  • currently this is not a good option for react native: caniuse.com/#feat=fetch
    – circuitry
    Commented Dec 19, 2016 at 22:52
  • 1
    Of course you can use fetch with React Native (I do) The link you provide shows browser compatibility. React is not a browser (hybrid) technology, so you can just include fetch via npm.
    – Plaul
    Commented Jan 10, 2017 at 14:12
  • 1
    For anyone thinking about using fetch in your frontend, please consider that there is no IE support unless you use some sort of polyfill like github.com/github/fetch, which even then is limited to IE 10+
    – Omegalen
    Commented Apr 1, 2017 at 7:02
  • 2
    If you're using React these days you're probably (should be) using Babel anyway so fetch is fine.
    – igneosaur
    Commented May 25, 2017 at 10:46
8

I would not use JQuery, since AJAX calls is actually not that complex and JQuery is a pretty big dependency. See vanillajs' note on doing AJAX calls without libraries: http://vanilla-js.com/

2
  • Using jQuery isn't advised, I prefer to use fetch.
    – AmerllicA
    Commented Dec 26, 2017 at 17:35
  • 1
    Indeed. ‘fetch’ are these days the goto solution for doing HTTP requests 👍 Commented Dec 27, 2017 at 19:31
2

I definitely proffer you to use Fetch API. It is very simple to understand, supports all methods and you can use async/await instead of promise/then and call back hell.

For example:

fetch(`https://httpbin.org/get`,{
    method: `GET`,
    headers: {
        'authorization': 'BaseAuth W1lcmxsa='
    }
}).then((res)=>{
    if(res.ok) {
        return res.json();
    }
}).then((res)=>{
    console.log(res); // It is like final answer of XHR or jQuery Ajax
})

In better way or async/await way:

(async function fetchAsync () {
    let data = await (await fetch(`https://httpbin.org/get`,{
                                method: `GET`,
                                headers: {
                                    'authorization': 'BaseAuth W1lcmxsa='
                                }
                            })).json();
                      console.log(data);
})();

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.