What the Fetch
Tags: javascript, es6, data, ajax
Published: 2018-07-21 03:20:14

---
title: What the Fetch
published: true
description: A primer on the new Fetch API
tags: JavaScript, ES6, data, AJAX
cover_image: https://thepracticaldev.s3.amazonaws.com/i/o0ptmhbznps82tfxehg8.jpg
---
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](https://jsonplaceholder.typicode.com/) we are going to retrieve a JSON file and append the incoming data to the DOM:

```javascript
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));
};

```

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.  

```javascript

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));
};

```

The resultant output would be 

![PUT Request](https://thepracticaldev.s3.amazonaws.com/i/db34n7rs571jeay0k58x.png)

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](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).  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.