Fetch API

Nov 5, 2018 · 314 words · 2 minute read ajax http

A HTTP library is still a common plugin to include on a project. Depending on what I am working on I will still use jQuery to make some of these requests or include a library like Axios to handle the requests.

If you are looking for a way to not include third-party scripts and work with native browser features Fetch will be something that you want to start to look at for including in your project.

Lets take a look at a native way to make a GET request before fetch.

var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var resp = request.responseText;
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

The example above is readable but it just always felt so like too much for me. Part of it is I would never remember any part of this. Thank you to You Might Not Need jQuery for the example.

Now, let us look at some examples of Fetch. First, we have to link to browser support. Edge and IE are lacking if you need to still support some of those browsers still.

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))

If the .then looks unfamiliar to you. It is best to start with reading Promise - JavaScript | MDN and learning over at MDN. Once, I started to understand promises. It made Fetch all that much easier to understand and to play with.

Fetch actually has really good browser support so you can start using it now. Here are some more resources on Fetch - Can I Use: Fetch - How to Use the JavaScript Fetch API to Get Data - Introduction to the Fetch API