Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajaxStart and ajaxStop equivalent with fetch API

I'm trying to migrate my API calls from using jQuery ajax to using the Fetch API.

I was using jQuery ajaxStart and ajaxStop to display a loading spinner during server calls.

I'm running several parallel server requests, I want the spinner to start when the first request start and to stop when the last request settled.

It was pretty straight foward with jQuery. However, I can't find a similiar technique using the fetch API. Any ideas ?

like image 757
Romain Lebascle Avatar asked May 13 '16 05:05

Romain Lebascle


People also ask

Which is best ajax or Fetch?

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 better than XMLHttpRequest?

Conclusions. The fetch API is an easier way to make web requests and handle responses than using an XMLHttpRequest.

What is Fetch API?

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.


2 Answers

You can use Promise to notify when fetch is called and completed

var params = {
  a: 1,
  b: 2
};

var data = new FormData();
data.append("json", JSON.stringify(params));

var currentRequest = new Request("/echo/json/", {
  method: "POST",
  body: data
});

var start, complete;
var fetchStart = new Promise(function(_start) {
  start = _start;
})

var fetchComplete = new Promise(function(_complete) {
  complete = _complete;
});
// do stuff when `fetch` is called
fetchStart.then(function(startData) {
  console.log(startData)
});
// do stuff when `fetch` completes
fetchComplete.then(function(completeData) {
  console.log(completeData)
});

var request = fetch(currentRequest);

[request, start({
    "fetchStarted": currentRequest
 })].shift()
.then(function(res) {
  if (res.ok) {
    // resolve `fetchComplete` `Promise` when `fetch` completes
    complete({
        "fetchCompleted": res
     })
  };
  return res.json();
})
.then(function(data) {
  document.body.textContent = JSON.stringify(data)
})
.catch(function(err) {
   // if error, pass error to `fetchComplete`
   complete({
     "fetchCompleted": res,
     "error": err
   });
});

jsfiddle https://jsfiddle.net/abbpbah4/18/


See also Fetch: POST json data

like image 107
guest271314 Avatar answered Nov 14 '22 04:11

guest271314


Just start your spinner before the call to fetch and stop it in the finally

state.showSpinner = true;
Promise.all([fetch(url1), fetch(url2)])
  .then(success => console.log(success))
  .catch(error => console.error(error))
  .finally(() => state.showSpinner = false);
like image 24
sritmak Avatar answered Nov 14 '22 04:11

sritmak