Handling ajax with React

55,305

Solution 1

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)
    });
  },

Solution 2

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

Solution 3

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

fetch('/api/getSomething').then(function() {...})

Solution 4

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/

Solution 5

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);
})();
Share:
55,305
user2442241
Author by

user2442241

Updated on April 20, 2020

Comments

  • user2442241
    user2442241 about 4 years

    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?

  • ivarni
    ivarni almost 9 years
    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.
  • PythonIsGreat
    PythonIsGreat almost 9 years
    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.
  • thom_nic
    thom_nic over 8 years
    On the topic of jquery being huge: alternatives include superagent and reqwest. Both have very similar APIs but superagent is only 10kB by comparison.
  • gtournie
    gtournie over 8 years
    you can just add the ajax part of jQuery: stackoverflow.com/questions/4132163/…
  • Adrian Lynch
    Adrian Lynch about 8 years
    How do you handle cancelling an in-flight request?
  • IntoTheDeep
    IntoTheDeep over 7 years
    I got $ is not defined
  • circuitry
    circuitry over 7 years
    currently this is not a good option for react native: caniuse.com/#feat=fetch
  • Plaul
    Plaul over 7 years
    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.
  • Omegalen
    Omegalen about 7 years
    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+
  • igneosaur
    igneosaur almost 7 years
    If you're using React these days you're probably (should be) using Babel anyway so fetch is fine.
  • AmerllicA
    AmerllicA over 6 years
    Using jQuery isn't advised, I prefer to use fetch.
  • AmerllicA
    AmerllicA over 6 years
    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.
  • Emil Ingerslev
    Emil Ingerslev over 6 years
    Indeed. ‘fetch’ are these days the goto solution for doing HTTP requests 👍