How to Fetch

Quick basic tutorial on the “Fetch” api

Alexander Schnapp
3 min readJul 3, 2017

Fetch: ES6’s more elegant version of AJAX that uses promise. It is often confusing when you first use it for anything that is not a simple “GET” request. Here is a link to the docs about “fetch” on MDN:

The basic structure of Fetch:

fetch(<url>, {parameters object});

The parameters object is where you include all the content of your “request”. For example: commonly used parameters like method, headers and body all belong in there. Here is an example fetch at its simplest form:

fetch('/', {
method: 'GET'
});

Let’s try something more complicated:

fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({body: 'hello'})
});

Extracting data out of a fetch

As mentioned before, the fetch api is a promise, and it returns a promise. To extract data from a fetch, you’ll need not one, but two then’s. Here’s an example:

fetch('/', {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({body: 'hello'})
}).then(response => { //then #1
return response.json();
}).then(responseJson => { //then #2
console.log(responseJson); //you'll see the response here
}).catch(error => {
//error clause
console.log(error);
});

Inside then #1 you can extract all the metadata that comes with the fetch. The metadata contains headers like the status code, url, and type. Also inside this ‘then’, you get to decide what to do with your data. Here are two examples: 1: If you’re expecting a JSON object, you do return response.json(), and 2: if you’re expecting a text object, you would do return response.text(). Keep in mind that ‘.json()’ and ‘.text()’ returns a promise, so don’t be surprised when you see a weird object that isn’t the data you’re expecting when you console.log it.

Common Gotchas:

  1. As mentioned, there are two thens. You will not get the data you’re expecting if you only use one.
  2. 400s and 500s status codes do not go into the error clause. The error clause returns a fetching error, and a server responding to your request does not count as an error. If you want to filter out 400 or 500 status codes, do this:
fetch('/', {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({body: 'hello'})
}).then(response => { //then #1
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
} else {
return response.json();
}

}).then(responseJson => { //then #2
console.log(responseJson); //you'll see the response here
}).catch(error => { //error clause
console.log(error);
});

That’s it! If you want more docs, here is a great piece on google developers: (the source for the above example)

Happy fetching!

--

--