Introduction to Javascript Fetch API
--
As the weeks were passing by at Flatiron School it became clear that the module based on Javascript was going to be a challenge. To get a better understanding of what was so complex about this language, I asked my classmates who had taken that module previously what they found the most taxing. A lot of the responses involved how tough learning the concepts around the Javascript Fetch was. In order to prepare for this difficult task ahead, I decided to write this blog to gain a better understanding and share my finding with those who might be in my position one day.
Dealing with JS’s asynchronous HTTP requests
Before diving into the breakdown of fetch I want to educate those who are new to Javascript on what asynchronous HTTP requests are and how to deal with them. To do that one must become familiar with promises.
In most programming languages, operations happen in order (sequentially). The first line must be executed before we can move on to the next line. But with JavaScript, we have multiple operations that are running in the background/foreground, and as you know, we cannot have a web application that freezes every time a user interacts with the application.
JavaScript is single-threaded, meaning that two bits of scripts cannot run at the same time; they have to run one after another. HTML 5 Rocks summarizes promises in a great way:
JavaScript is single threaded, meaning that two bits of script cannot run at the same time, they have to run one after another. In browsers, JavaScript shares a thread with a load of other stuff. What that stuff is differs from browser to browser, but typically JavaScript is in the same queue as painting, updating styles, and handling user actions (such as highlighting text and interacting with form controls). Activity in one of these things delays the others.
As a human being, you’re multithreaded. You can type with multiple fingers, you can drive and hold a conversation at the same time. The only blocking function we have to deal with is sneezing, where all current activity must be suspended for the duration of the sneeze. That’s pretty annoying, especially when you’re driving and trying to hold a conversation. You don’t want to write code that’s sneezy.
Promises prevent developers from writing ‘sneezy’ code which is really important for fetching API’s its main purpose is to make requests for assets or data.
Back to Fetch
The fetch()
method returns a Promise
that resolves the Response
from the Request
to show the status (successful or not).
So in short, we first define the path (Fetch), second, request data from the server (Request), thirdly define the content type (Body), and lastly, we access the data (Response).
I recommend using the catch method when writing your code. The catch method is a callback method that will intercept any errors occurring during the execution of the request.
Working With an Example
So now let’s talk through an example. For this example, we’ll use the fabulous JSONplaceholder site to fetch posts data. After creating your index.html file and adding the HTML skeleton you will need to create a button which I named Get API Data.
Once finished you will need to add an event listener. An event listener basically attaches an event handler to the specified element. In this case, the event listener will be looking for the id with the text “getPosts” and once it’s clicked on will call the function #getPosts.
Then you will need to create your function which will look similar to the function below. So for every fetch()
whose data you want to show or manipulate you will need at least two then()
methods: the first to return the response method that retrieves your data, and the second then to actually work with the data.
And just like that, you have created a button which when clicked on will return a post!
Go Forth and Fetch
Bam! There you have it, the very basics of fetch()
. I highly encourage reading the MDN docs, the Google and javascript.info articles as well. But the best way to learn is to do, so get out there and build a fetching new site!