What the Fetch

ignoreintuition

Brian Greig

Posted on July 21, 2018

What the Fetch

This fetch API is pretty nifty. If you have worked with JavaScript's XMLHttpRequests in the past or if you had to rely on libraries like jQuery or Axios you will really appreciate what fetch does. Fetch is:

  • Easy to set up
  • Promise based
  • Configurable

The main disadvantage is that at the time of this writing is that it is poorly supported so it will require you to use ployfills to support older browsers. In the meantime, you should definitely be getting your hands dirty with this API. Let's start with a basic example. Using JSON Placeholder we are going to retrieve a JSON file and append the incoming data to the DOM:

var url = `https://jsonplaceholder.typicode.com/photos`;

getData(url)
  .then(data => {
    data.forEach( e => {
      var div = document.createElement("div"),
          content = document.createTextNode(e.title);
      div.appendChild(content);
      document.getElementById('content')
        .insertAdjacentElement('beforeend', div);
    })
  })
  .catch(error => console.error(error));

function getData(url){
  return fetch(url, {
      method: 'GET',
    })
    .then(response => response.json())
    .catch(error => console.error(`Fetch Error =\n`, error));
};

Enter fullscreen mode Exit fullscreen mode

The API call takes two parameters. The first is the URL for the server API endpoint. The second is a init object where we will set any unique configurations. In this simple example we are just setting the HTTP request method.

As mentioned above this is all promise based. This affords us the ability to allow execution of the code to continue asynchronously while the data is being retrieved from the server. The getData function will send the GET request to the server. Once the data is returned the chained then() function will execute passing a promise with the JSON formatted response back to the originating method. That method can then take data and loop through every value appending each value individually to the DOM.

In our example we submitted a GET request but you can use any of the standard methods (GET, POST, DELETE, PUT) that are required by your application.


var url = `https://jsonplaceholder.typicode.com/posts/1`;

postData(url)
  .then(data => {
    console.log('complete')
  })
  .catch(error => console.error(error));

function postData(url) {
  return fetch(url, {
    method: 'PUT',
    body: JSON.stringify({
      id: 1,
      title: 'This is a Test',
      body: 'Some Random Text',
      userId: 1
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8"
    }
  })
.then(response => response.json())
  .catch(error => console.error(`Fetch Error =\n`, error));
};

Enter fullscreen mode Exit fullscreen mode

The resultant output would be

PUT Request

There are a other options you can pass to the second optional parameter in the Fetch method such as access controls (cors, same-origin), caching, etc. These options are well documented on the MDN Page. Feel free to research each of these as they apply to your particular use case.

This was just a short primer to familiarize you with the fetch API if you hadn't been exposed to it before. Hopefully this API will remove some of the stigma associated with querying API endpoints that has been the norm for far too long. Godspeed.

💖 💪 🙅 🚩
ignoreintuition
Brian Greig

Posted on July 21, 2018

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

Sign up to receive the latest update from our blog.

Related

What the Fetch
javascript What the Fetch

July 21, 2018