Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display spinner during AJAX call when using fetch API

In my project I am migrating to React and so not loading JQuery. Since I don't have JQuery anymore, for AJAX calls I am using fetch. With JQuery I can hook the start and end of AJAX calls so it's very easy to change the cursor to a spinner. I can't find similar hooks in fetch. Is there a way to do this other than changing it in each individual AJAX call?

Lots of Googling just kept finding answers about... JQuery.

like image 638
Jim Archer Avatar asked May 04 '17 20:05

Jim Archer


People also ask

Should I use fetch API or Ajax?

Fetch is compatible with all recent browsers including Edge, but not with Internet Explorer. Therefore, if you are looking for maximum compatibility, you will continue to use Ajax to update a web page. If you also want to interact with the server, the WebSocket object is also more appropriate than fetch.

Is fetch API and Ajax same?

Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP. The fetch specification differs from jQuery.ajax() in the following significant ways: The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500.

Does Ajax use Fetch?

Fetch is an interface for making AJAX calls in JavaScript. It is implemented widely by modern browsers and is used to call an API. Calling fetch returns a promise, with a Response object.

How fetch data from API and display in JavaScript?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.


1 Answers

Fetch in thenable, you can add spinner stop function in then(), that is called after response is received. And wrap it in another function for headers and hooking.

function ajax(someUrl, method) {
    var myHeaders = new Headers();

    var myInit = { 
        method: method,
        headers: myHeaders
    };
    showSpinner();

    return fetch(someUrl, myInit).then(function(response) {
        //... do some with response
        hideSpinner();

        return response;
    }).catch(function(error) {
        //... tell the user the request failed and hide the spinner
        hideSpinner();

        return error;
    });
}

ajax('example.com').then(function(response) {
    // ...
}).catch(function(error) {
    // show error
});
like image 133
rie Avatar answered Oct 17 '22 10:10

rie