Breaking Down Fetch

Cathy D'Onofrio
3 min readAug 18, 2020
Photo by Jeremy Perkins on Unsplash

When we were first taught how to fetch in Javascript, I was a bit confused. I understood its overall concept, but I had trouble getting the exact logistics of it all straight beyond the GET method. So, I attempted to break it all down here. Note that this is just a breakdown of the methods themselves, not necessarily all of the other functions they interact with.

Fetch Overview

  1. Use fetch to send our request to an API, which returns a promise
  2. Call .then() to access the response the API provided, then return it as JSON
  3. When the promise gets resolved, we get the data as an object and display it to the DOM

There are 4 main methods: GET, POST, PATCH, and DELETE.

GET

The GET method is described above as it is the default method. It essentially retrieves information from the database in a digestible format.

After that, we can do what we’d like with the object. In the below example, I used a function that would iterate over the array of objects returned.

getData = () => {
fetch(url)
.then(response ⇒ response.json())
.then(dataCollection ⇒ renderDataFromDatabase(dataCollection))
}
getData();

POST

For POST (ie, sending data a user submitted into the database), we need to pass a configuration object into the database.

fetch(URL, configObj)

The configuration object includes:

  • Specifying the HTTP verb — in this case, POST
  • Metadata (a set of data that describes and gives information about other data), most commonly a header and a body.
  • Headers: Most commonly, we’d include the following:
  • “Content-Type”, which specifies format data is being sent in. Since we are using json, we would specify “application/json”
  • “Accept”, to confirm what type of data we will accept in return
  • Body: includes the data we are sending back to the database. We need to convert the objects into strings for JSON, so we need to stringify it. For separation of concerns, it’s not a bad idea to define the object separately, as below.

Then, you would handle the fetch request.

let dataToPost = {
key1: value1,
key2: value2
}
let configObj = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(dataToPost)
};
fetch(url, configObj)
.then(response => response.json())
.then(newData => renderSingleItem(newData))

Here, I used another aspirational function that would each individual item to the page in the way I choose to manipulate it. I’d call this on the final line of the fetch request so that a newly created item would appear on the page as soon as I submit it without refresh.

PATCH

Patch was the method that tripped me up the most when I first learned it, because IDs come into play. Patch would need to be used if you are editing any existing item, whether it’s in a form, or if you’re incrementing a ‘likes’ button via a counter.

My preferred way to do this would be to add a class or a data ID (via dataset) when I create the function to render each individual object and manipulate them. This way, the DOM updates and I can access it later in the event listener.

In comparison to a POST request, the major changes are:

  • Method: “PATCH”
  • Adding an ID to the first argument of Fetch
let dataToPatch = { //here, we are replacing the previous total likes after another user clicked on the event listener
likes: newLikesValue
}
const configObj = {
method: "PATCH",
headers: {
"content-type": "application/json",
"accept": "application/json"
},
body: JSON.stringify(dataToPatch)
}
fetch(Url + Id, configObj)
.then(response => response.json())
.then(updatedLikesObj => {likeSpan.innerHTML = `${updatedLikesObj.likes} likes`})
//here, we are assuming that the total likes are in a span we grabbed off the DOM, and we replace it with the new likes object we passed back to the database

DELETE

Delete is one of the more straightforward requests, as long as you’ve properly identified the ID.

In contrast to Patch (which also requires an ID), the only differences are:

  • Method: “DELETE”
  • Removal of the final line of the fetch sequence, since you are not returning anything back from the database.
const configObj = {
method: 'DELETE',
headers: {
"content-type": "application/json",
"accept": "application/json"
},
}
fetch(deleteUrl + idToDelete, configObj)
.then(response => response.json())

I hope this breaks down the methods of a fetch request a little bit more!

Resources:

https://css-tricks.com/using-fetch/

--

--