That is sooooo Fetch!!!

Joseph Patterson
5 min readMay 28, 2020

A quick look at Javascript’s fetch request

published by Joey Patterson

Anybody who is new to javascript will likely come across the fetch request pretty early on. In the early days of JS, developers were able to provide smatterings of interactivity to otherwise static pages. The explosion of the language’s popularity in the last decade led to an increase in functionality. Now javascript is used to make entire frontend applications. Being a frontend language, it needs a way to access data. Say hello to the fetch request.

Fetch Basics

According to MDN Web docs, “The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses”. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

What does this mean exactly? Let’s look at a simple fetch request and break it down.

Here we see a fetch() function accepting the url http://localhost:3000/items as its argument. This is javascript’s way to interact with an API (Application Program Interface). In this case, it is making a request to a Ruby Rails database and asking for all of the item data contained therein. When fetch does this successfully, the response is returned as a promise. Promises are asynchronous objects (of course everything is an object in Javascript) and resolve to return a value at some point in the future. This is incredibly useful when code starts to get unruly as asynchronous operations do not need to run in order to be compiled. The data contained in the response is not yet readable by Javascript so we have to convert it into JSON. The third line of code is taking the converted data and then logging it to the console. It is always a great idea to console.log the data returned by a fetch request in order to know the exact structure of the object you are being returned. The raw json returned looks like this.

look at all those gitfiddles!!

The console.log will reveal how the data is structured for you to use.

Now we know we have an array of objects! Once we know we are getting the appropriate data, it is off to the races. There are a range of options available to access the key[value] pairs we want, but thats a lesson for another time. This is the most basic use of the fetch() request but there are other actions it can perform.

POST, PATCH, and DELETE

Fetch is just fine for accessing information yet it is capable of much more. There are three methods available to manipulate data.

POST — is used when you want to create data and send it to the backend.

PATCH — is used to edit changes to existing data.

DELETE — is used to destroy existing data.

Here is an example of how to make a POST request.

The fetch() starts the same as before but instead of only accessing the database, it is POSTing an item to it. The method call is POST followed by something called mode: ‘cors’. This will allow requests for assets on the same-origin and other origins which return the appropriate CORs headers. Headers interface of the fetch() allows you to perform various actions on HTTP request and response headers. We are letting it know that it is accepting the Content-Type from application/json. This brings us to the body. The body contains all the attributes needed to create a new item(I did not include the code where we are taking the values of the attributes from our form input elements). We need to use the JSON.stringify function to turn the Javascript data into a json string to send back. Just like in our first example the response has been promised and we must convert it to json. REMEMBER TO CONSOLE LOG THE RESPONSE. The results may surprise you.

The PATCH method is very similar to POST. By changing our method to PATCH in the fetch, we can take an existing object and edit its attributes to another value. The body contains the updated attribute(s) value which is stringified to JSON.

DELETE is the third option. DELETE is passed in as the method and the object you wish to delete is declared in the body.

Error Correcting

It is always good practice to add error handling and checks to a fetch. In creating a promise, you want to make sure it is being returned, and if not, why. Fetch has an ok flag that can say whether a response’s status code is successful.

fetch("http://localhost:3000/items")
.then(function(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}).then(function(response) {
console.log("ok");
}).catch(function(error) {
console.log(error);
});

The .catch block then console logs the error messages. This code is verbose and not reusable. A better option would be to write a generic function that can be used on any fetch () call.

function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}

fetch("http://localhost:3000/items")
.then(handleErrors)
.then(function(response) {
console.log("ok");
}).catch(function(error) {
console.log(error);
});

This makes the code nice and DRY.

Getting a fetch() request to work properly can be a bit of a chore. Adding error messages can help you quickly see and assess any problems.

Don’t Sleep On Fetch

The fetch() request is a powerful tool. It allows Javascript to increase functionality from simply spicing up a static page to accessing, adding, and manipulating data from an API. This is blog is meant to provide a basic intro to fetch. Please take the time to dive deeper with these great resources.

--

--