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?

user2442241
  • 935
  • 3
  • 11
  • 13

5 Answers5

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)
    });
  },
PythonIsGreat
  • 7,529
  • 7
  • 21
  • 26
  • 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 May 01 '15 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. – PythonIsGreat May 02 '15 at 02: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 Sep 08 '15 at 17:57
  • 3
    you can just add the ajax part of jQuery: http://stackoverflow.com/questions/4132163/is-there-only-ajax-part-of-jquery – gtournie Dec 11 '15 at 07:05
  • 3
    I got $ is not defined – IntoTheDeep Aug 10 '16 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

Mohammad Arif
  • 6,987
  • 4
  • 40
  • 42
  • 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 Dec 26 '17 at 17:41
14

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

fetch('/api/getSomething').then(function() {...})
Alex Ivasyuv
  • 8,585
  • 17
  • 72
  • 90
  • 2
    How do you handle cancelling an in-flight request? – Adrian Lynch Mar 27 '16 at 10:28
  • currently this is not a good option for react native: http://caniuse.com/#feat=fetch – circuitry Dec 19 '16 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 Jan 10 '17 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 https://github.com/github/fetch, which even then is limited to IE 10+ – Omegalen Apr 01 '17 at 07:02
  • 2
    If you're using React these days you're probably (should be) using Babel anyway so fetch is fine. – igneosaur May 25 '17 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/

Emil Ingerslev
  • 4,645
  • 2
  • 24
  • 18
1

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);
})();
AmerllicA
  • 29,059
  • 15
  • 130
  • 154