Sitemap

How to Use Fetch in JavaScript

Fetch is a function in JavaScript used for interacting with a database and APIs (Application Programming Interface). These interactions include retrieving, uploading, editing and deleting data.

5 min readJan 25, 2021

--

Image Source: ba-reps.com

You can think of Fetch like the literal game of playing fetch with your dog:

  • You throw the stick and see where it lands (Fetch the URL).
  • Your dog runs after the stick and has it in their mouth to eventually bring it back (a promise to do what you want).
  • Your dog brings it back to you and delivers it to you, as you would like (you receive the data and can use it however you’d like).

Fetch Requests

To understand Fetch, you must understand the four types of requests that Fetch provides us with:

  1. GET requests — used for retrieving or “fetching” data.
  2. POST requests — used for uploading or adding data.
  3. PATCH / PUT requests — used for editing data that is already in the database.
  4. DELETE requests — used for deleting a piece of data.

Fetch accepts two arguments. The first is a string URL and the second is an optional argument that includes information regarding the request you want to make to the database or API. If you are only trying to get data from an API, you do not need to use the second argument.

fetch("http://example-Url-of-an-API")

Promises

If you enter the above code into your console, you’ll get a promise. In fact, a successful Fetch request will always return a promise. A great way to think of a promise is as an IOU. This IOU guarantees that something will be returned to you. Along with a promise, comes a response, but how do you turn that response into usable data for applications?

Want to read this story later? Save it in Journal.

You do this with a .then statement, that converts the data into something readable and digestible with JSON. JSON or JavaScript Object Notation is the format for how you transmit data through web applications.

Here is an example of our Fetch request example with its first .then statement:

fetch("http://example-Url-of-an-API")
.then(response => response.json())

The first .then statement is always the same! It parses out the returned promise in JSON.

When you call .json() on a promise, in return, you get yet another promise. This second promise is imperative because it allows you to see and use the data you return in a way that you see fit.

In the below example the data from the API is being logged to the console via the the second promise in the Fetch request.

fetch("http://example-Url-of-an-API")
.then(response => response.json()
.then(data => {
console.log(data)
}
)

Now Lets Go Through the 4 Different FETCH Requests You Will Be Making

For the purpose of this blog and simplicity, I created a simple movie database in my db.json file in VSCode and ran it on localhost:3000 using the command json-server --watchdb.json.

This is what my database looks like:

Press enter or click to view image in full size

GET Request

GET requests are used for retrieving or “fetching” data from an API:

fetch("http://localhost:3000/movies")
.then(response => response.json())

For GET requests, a second argument is not necessary.

POST Request

POST requests are used for uploading or adding data to an API:

const configObject = {
method: ‘POST’,
headers:
{
“Content-Type”: “application/json”,
“Accept”: “application/json”
},
body: JSON.stringify({
title,
release_date,
image_url,
rating
})
}
fetch("http://localhost:3000/movies", configObject)
.then((response) => {
return response.json()
}).then(function (object) {
return object
})

configObject is an object I created to be the second argument. In this object, I have three key-value pairs:

  1. The first is the request I am making to the database or backend. In this case, it’s a POST request.
  2. Next is the headers, which contains information about the data being sent. Content-type states what format the data will be sent in. Accept simply means what format you’ll accept the data in.
  3. The last key-value pair represents the information about the attributes needed to create a movie object in a stringified form.

After creating configObject, I added it in as the second argument in the Fetch request. The Fetch request will return the data, it will accept the promise with a .then response and parse the information into JSON. Then .json() will return another promise that you can work with how you see fit.

PATCH Request

PATCH / PUT requests are used for editing data that is already in the database.

fetch(`http://localhost:3000/movies/${movieId}`, {
method: ‘PATCH’,
headers:
{
“Content-Type”: “application/json”,
},
body: JSON.stringify({
image_url,
rating
})
})
.then((response) => {
return response.json()
}).then(function (object) {
return object
})

Instead of creating a configObject like in the POST request, I wanted to show you the syntax of what it looks like if you decide to insert that data inside of the Fetch request. This is in lieu of abstracting it in a variable and including it in the second argument after the link.

Since I am updating information, I am going to be using a PATCH method. For PATCH requests the link is dynamic, you make a link dynamic by using back-ticks (``). I did this because I want the PATCH request to be applicable to any movie with any Id in our database and to do this I need to interpolate the ${movieId}.

I also changed the body section of the request. I did this because in my application I only want certain attributes to be changeable. In this case it’s the image_url and the rating. I omitted the title and release_date since those attributes of a movie usually do not change.

DELETE Request

DELETE requests are used for deleting a piece of data:

fetch(`http://localhost:3000/movies/${movieId}`, {
method: “DELETE”,
}).then(response => response.json())
.then(response => { return response })

Like the PATCH request, I put back-ticks around the link so that I can interpolate the ${movieId}. Since I am just deleting data and I don’t expect to get any information back from the API, I don’t need to include headers or a body.

Don’t fret if this all seems like a lot of information at first. It takes time and practice to wrap your ahead around Fetch. Don’t forget that the documentation is out there and accessible on the internet at all times. I have found the MDN Web Docs on using Fetch very helpful:

That being said, when you are starting out try not to copy and paste from the documentation. Instead write everything out on your own, while looking at the documentation. This will help you better understand what you are writing and will engrain the syntax in your memory.

Your turn… Fetch!

--

--

No responses yet