DEV Community

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')
Enter fullscreen mode Exit fullscreen mode

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);
 });
Enter fullscreen mode Exit fullscreen mode

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);
Β  });
Enter fullscreen mode Exit fullscreen mode

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);
Β  });
Enter fullscreen mode Exit fullscreen mode

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

https://developers.google.com/web/updates/2015/03/introduction-to-fetch

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Latest comments (3)

Collapse
 
opeyemi2018 profile image
Opeyemi Odunayo

πŸ₯Š

Collapse
 
fericoder profile image
Fariborz

Great❀

Collapse
 
karenefereyan profile image
Efereyan Karen Simisola

Amazing as always