Let’s Go Fetch() Some Stuff!
Chukwuma Anyadike
Posted on November 1, 2022
As software engineers we write applications which involve interacting with API’s (application programming interface). Special functions such as fetch() allow us to upload and download data from remote sources. Fetch can also allow us to modify already uploaded data. By allowing our code to interact with an API it makes our webpages more dynamic. This means that the content and even the appearance of our applications can vary depending on the data that we fetch().
This is how fetch() works. The fetch() method starts the process of fetching a resource from the network and returns a Promise which is fulfilled once the response is available. The Promise resolves to the response object which represents the response to your request.
This is a prototypical fetch request:
fetch(“http address”)
.then(response => response.json())
.then(data=> callback (data))
Note that “http address” is passed as an argument into the fetch() method. The fetch sends an HTTP GET request and returns a Promise object. Once the promise is fulfilled a response object is sent. The then() method takes response => response.json()) as a callback function for fulfilled and rejected cases of the promise. It converts the response object into a regular object (data object). A second then() method takes callback function involving data as an argument. Data is the regular object (converted from the response object) which is returned which itself can be passed through a callback function to run the necessary code manipulating this data object. Technically the data object is an array of objects.
Now, that I have explained the fetch() method let us have a little fun and fetch() some stuff. For one of my projects, I designed an application which designs workouts. This involves fetching a lot of exercises. Here is what a single exercise looks like on my API.
{
"chest": [
{"name": "Bench press",
"muscles": "pectoralis major, deltoids, triceps",
"image": "https://thumbs.gfycat.com/AngelicWhirlwindKronosaurus.webp",
"id": 1
}
]
}
Each of my exercises is an object on JSON server. JSON stands for “JavaScript Object Notation” which describes the way this object is displayed with each word in quotations including the key names. JSON also sounds like the name of a 90’s R & B singer, but that has nothing to do with coding. Anyway, lets get back to the topic at hand. The question at this point should be “what are we doing with data like this?” I personally want to use this data for an exercise planning application so that all software engineers can work out with purpose before or after sitting in a chair for hours writing or editing code.
The first thing to do is write a fetch() method. It goes something like this.
fetch(“http://localhost:3000/chest”)
Here we are using “http://localhost: 3000/chest” as our http address which is passed as an argument. It tells us where to get our data. Then what? A Promise object is returned. Once there is a response then the response object is returned.
Note that the fetch() method is an asynchronous function. When a response is available then the promise is fulfilled. One needs to wait for a response so that you can fulfill the promise. Meanwhile other lines of code in your program are still running, hence, asynchronous. Conversely, synchronous functions where lines of code run sequentially.
Now that I have finished talking, there has been a response and the promise is fulfilled. That is where our next line of code comes in.
.then(response => response.json())
This line of code takes the response object (which is in JSON format) and converts it to a JavaScript object. This regular object can be passed into our next line of code as a data object. We can move on to our next line of code which involves taking the data object from the response and making use of it via a callback function.
.then(data=> callback (data))
The question now should be “what am I going to do with this data?” I want to display the name of the exercise, purpose of the exercise, and show a picture of how it is done. To do this I will have to create html elements which are displayed in the browser. Let us see what this looks like.
fetch(“http://localhost:3000/chest”)
.then(response => response.json())
.then(data=>{
data.forEach ((piece)=>{
let ex = document.createElement('p')
ex.id = piece.name
ex.style.color = "blue"
ex.textContent = piece.name.toUpperCase()
let ul = document.createElement('ul')
let description = document.createElement('p')
description.textContent = `${piece.name} focuses on these muscles: ${piece.muscles}.`
let image = document.createElement('img')
image.src = piece.image
ul.append(description, image)
ex.append(ul)
exerciseList.append(ex)
})
.catch((error)=>alert("There is an error"))
Note that the last line of code is a catch() method. This returns a Promise in cases of rejection.
In summary, I am using a fetch function to obtain data from an API. This data is in the form of an array of objects. The array represents a body part such as chest containing different exercises. A piece of data in this case is a single exercise. I am iterating through the array using forEach and displaying each exercise by name, muscles worked, and image on the browser.
It ended looking like this below.
Overall, I am satisfied but this dude’s grip on the bar is somewhat narrow. But if it works for him, then more power to him. Overall, the man’s technique is solid.
This is only one exercise. My API contains around seventy exercises. Using a combination of fetch() and an array iterator method I can generate this type of display for every exercise on JSON server.
I hope that we all see the power and utility of the fetch() method to make amazing things happen. One can improve one’s health and quality of life with the right tools. Until next time, stay strong and fetch() some more stuff.
Posted on November 1, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 2, 2024
September 19, 2024
August 20, 2024