Fetch API 101

yogesnsamy

Yogeswari Narayasamy

Posted on June 10, 2019

Fetch API 101

Credit: This sharing is based on my learning from the super awesome The Net Ninja's JavaScript Course on Udemy.

Pre-requisite: Some (or more) good knowledge of promises is necessary to understand fetch.

What is fetch?

Simply put it's the modern way of getting data/resources from a server. fetch is supported by promises under the hood.
It replaces the use of XMLHttpRequest in making asynchronous calls to networks.

Due to its newness, fetch doesn't work on all browsers yet.

Calling fetch

To use fetch, simply type fetch() and use one of the following as its parameter:

  • an API endpoint - for example fetch("https://jsonplaceholder.typicode.com/todos/1");
  • a local resource - for example fetch("todos/vela.json");

fetch returns a promise which either resolves or rejects which we handle using .then() and .catch()

So a fetch call would look something like below:

fetch()
  .then(response => {
    //promise resolved, do something with result
  })
  .catch(err => {
    //promise rejected, handle the error
  });

Accessing the fetch response

When a promise resolves, we don't have access to the data we want yet.

For example, let's run the following code that will randomly retrieve a piece of advice each time:

fetch('https://api.adviceslip.com/advice')
  .then(response => {
    //promise resolved, do something with result
    console.log('Resolved: ', response);
  })
  .catch(err => {
    //promise rejected, handle the error
    console.log('Rejected: ', err);
  });

The code returns a response object. We will now have to call the json method available on the response object to access the returned data.

Calling the json Method on the Response Object

As shown above, json is a method on the response object (which we can see by expanding the proto key).

We need to call the json method on the response object to get the data we need.

When the json method is called, another promise will be returned which can either be resolved or rejected. So we need to chain the first call to another to manipulate the resulting data.

The way to do this is as below:

fetch('https://api.adviceslip.com/advice')
  .then(response => {
    //promise resolved, do something with result
    console.log('Resolved: ', response);
    //new code
    return response.json(); 
  })
  //new code
  .then(data => {
    console.log(data);
  })
  .catch(err => {
    //promise rejected, handle the error
    console.log('Rejected: ', err);
  });

Output:

And this is ladies and gentlemen, how fetch works in a nutshell!

Three Steps to Remember While Working With fetch

  1. Call fetch("xyz");
  2. Call response.json() on the response
  3. Do something with the data

Note on the Response's HTTP Status Code

Take note that fetch doesn't fail even when we call an incorrect end-point/resource.

For example, calling a non-existent route like https://api.adviceslip.com/advicexx won't make the execution jump to the catch block! A resolve is still returned in this case but with the HTTP response code of 404 (instead of 200).

So it's a good idea to check the response's HTTP status code prior to calling json on it. For example using the following code:

fetch('https://api.adviceslip.com/advice<strong>xx</strong>')
  .then(response => {
    //promise resolved, do something with result
    console.log('Resolved: ', response);
//new code
    if (response.status === 200) {
      return response.json();
    }
    throw new Error('Resource not found');
  })
  //new code
  .then(data => {
    console.log(data);
  })
  .catch(err => {
    //promise rejected, handle the error
    console.log('Rejected: ', err);
  });

Output:

Please check out this entry on Stack Overflow for detailed information about fetch and catching errors: https://stackoverflow.com/questions/38235715/fetch-reject-promise-and-catch-the-error-if-status-is-not-ok

💖 💪 🙅 🚩
yogesnsamy
Yogeswari Narayasamy

Posted on June 10, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Fetch API 101
javascript Fetch API 101

June 10, 2019