Understanding Fetch API

person carlosrojasofolder_openUncategorizedaccess_time November 5, 2017

As we have seen previously, Service Workers are the best option to add special capabilities to our WebApp making our Apps feel like Natives when they are installed from a Mobile (Without entering App Store or Google Play Store).

The Service Worker allows you to add all this new functionality basically thanks to two APIs, the CACHE API, and the Fetch API. In this opportunity, we will focus on the Fetch API.

Asynchronous calls.

If you have a good time in the world of web development you know that the main way to make calls to servers and allow the update of parts of a page was XMLHttpRequest, something like this:

const xhreq = new XMLHttpRequest();

xhreq.open('GET', url);

xhreq.responseType = 'json';
xhreq.onload = () => { console.log(xhreq.response); };
xhreq.onerror = () => { console.error("Ops!"); };
xhreq.send();

But it has some disadvantages like the fact that we could only bring basically text and JSON objects.

You can read a bit more about this here.

Fetch

Fetch API is a new Web interface which seeks to simplify XMLHttpRequest and provide more features that facilitate the search of resources through the network.

Its basic use looks like this.

var myImage = document.querySelector('img');

fetch('someimage.jpg').then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

As you can see, it works as a promise and allows you to manage the response really easily. In addition, thanks to its Request and Response objects we will be able to have good control over the requests that we intercept in the network.

You can see its compatibility here.

Using it in the Service Worker.

Now we are going to use fetch in an event of our service worker to respond to our user with the cache content or the content of the network.

self.addEventListener(‘fetch’, function(e){
	e.respondWith(
		caches.match(e.request).then(function(response){
			return response || fetch(e.request);
 })
);
);
});

As you can see we have added new functionality to our Service Worker and therefore to our App without having excess code in it.

If you want to learn a little more about the great power of this API you can go here.

Well, I hope it is useful and see you in our next post.

Liked it? Take a second to support carlosrojaso on Patreon!