DEV Community

12 1

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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (3)

Collapse
 
opeyemi2018 profile image
Opeyemi Odunayo β€’

πŸ₯Š

Collapse
 
fericoder profile image
Fariborz β€’

Great❀

Collapse
 
karenefereyan profile image
Efereyan Karen Simisola β€’

Amazing as always

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay