Understanding fetch() API In JavaScript

Understanding fetch() API In JavaScript

Some decades ago, JavaScript developers were stuck with using XMLHttpRequest which is slightly confusing and more complex 😴, then some years later, jQuery (a JavaScript library) built an helper function to make writing ajax code more easier. And again, some years after this, the fetch() api was introduced 💥.

Introduction

The fetch api makes it easier to create asynchronous request and handle the response even more better than the good old XMLHttpRequest.

The main difference between XMLHttpRequest and fetch() is that fetch() uses Promises, which makes it cleaner and simpler to implement.

Getting started

The first thing you need to do when using the fetch API is to invoke the function with the url we want to query as the function parameter:

fetch('http://my_url.com/api/user')

Well, that's not the end of it, since fetch uses promise, we'll need to add a .then() function to grab our data;

But somehow, the first promise will also return another promise.

The reason for the second promise is because, the first one return the data along with some information we don't really need at the moment, so we use the second promise to get our raw data. Now the code look like this:

fetch('http://my_url.com/api/user')
.then(function (response){
     return response.json();
 })
.then(function (data){
    // Do something with data
    console.log(data);
 });

You'll notice the first promise has a .json() method, this is to specify that we are expecting a json data.


By default, fetch api uses GET method to access the url. We could add a second parameter (in form of an object) to the function to specify the method we want to use, such as POST, DELETE, PUT, e.t.c and also send some data along with our asynchronous request.

Here's how:

// Post Method With Data Example
fetch('http://my-url.com/user/details', {
    method: 'post',
    body: 'email=foo& password=bar'
  })
  .then(function (res) {
        return res.json();
    })
  .then(function (data) {
      // Do something with data
    console.log(data);
  });

For debugging sake we can add .catch() method to handle any error that might occur while sending our request:

// Adding .catch() to our previous code
fetch('http://my-url.com/user/details', {
    method: 'post',
    body: 'email=foo& password=bar'
  })
  .then(function (res) {
        return res.json();
    })
  .then(function (data) {
      // Do something with data
    console.log(data);
  })
  .catch(function (error) {
    console.log('Request failed, Error ' + error);
  });

Final Notes

This article is just to explain the basics stuffs you need to know about fetch().

"Quote Generator" - 👦🚀

In my next article, we'll get a bit more practical by learning how to build a random quote generator site using the fetch api.

P.s: Don't you think it'll be awesome if you share this with your friends on social media, how about you do that now 🙃

And finally below are some great references I'd gather if you want to further your reading on fetch(). Thanks for reading 👏

Resources

developers.google.com/web/updates/2015/03/i..

developer.mozilla.org/en-US/docs/Web/API/Fe..