DEV Community

Cover image for What the Fetch
Brian Greig
Brian Greig

Posted on • Edited on

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.

Top comments (8)

Collapse
 
rpalo profile image
Ryan Palo

Awesome write up! Thanks for laying out some clear examples. Bookmarking this for everytime I want to make an api call and can't remember exactly what the syntax is. :)

In case anyone's interested, the support for fetch is actually pretty good! Opera Mini and IE11 are the only browsers that need a polyfill.

Collapse
 
ignoreintuition profile image
Brian Greig

Good catch. Depending on your audience that is pretty decent coverage.

Collapse
 
bias profile image
Tobias Nickel

you might change the parameter 'e' to url in getData and postData, otherwise you will only use the 'url' from the outer scope.

other then that the methods are very handy and can help to write cleaner code.

thanks for sharing

Collapse
 
ignoreintuition profile image
Brian Greig

Good eye. I completely missed that because the code executed using the globally scoped variable. It is fixed now. Thanks.

Collapse
 
itsasine profile image
ItsASine (Kayla)

Making fetch happen

Collapse
 
alephnaught2tog profile image
Max Cerrina

When I loaded this page I was literally thinking "if there isn't a comment from Mean Girls"...!

Collapse
 
ignoreintuition profile image
Brian Greig

Truth

Collapse
 
bohdanstupak1 profile image
Bohdan Stupak

Hi! Thanks for the good article. I wonder tho if you already have a method postData which does PUT what will happen when you'll need a method which actually does POST.
Have a nice day! :)