DEV Community

Cover image for Demystifying Fetch()
sheenasany
sheenasany

Posted on • Updated on

Demystifying Fetch()

I have to admit, fetch was (and still is at times) the most difficult concept for me to wrap my head around. I've been reading countless articles, trusted and some not so trusted, watching tons of YouTube videos and speaking to many of my colleagues and instructors who have been attempting to help me demystify it in my brain. Why isn't my data parsing correctly? Why does my second promise come up with an error? Why does an error show when I use .forEach? Why is nothing showing on my webpage?! Why isn't this thing FETCHING?!

I understand your frustration. So I am going to attempt to break it down for those who are also having a difficult time grasping the most essential piece of code you need to understand in order to get anything working on your webpage.

A Little Background

The Fetch API can be used to get data from a local or remote file or a database from an API, or we can use it to push new data to a database in an API. It's similar to the XMLHttpRequest but fetch is most commonly used as a preferred method to access data because it's promise based, it works asynchronously to promise data and return the data when the page is fully loaded. There are a lot of other reasons why fetch is better than XMLHttpRequest, but you don't need to know that now. Let's just focus on the basic stuff.

I know this already seems like a bit much, but if you don't know about asynchronous JavaScript, I suggest you take some time to watch this video. It gives a great simplified explanation of what I mean when I say asynchronous JavaScript and touches on fetch as well. The more information, the better, right?

Syntax

The fetch command is usually one of the first lines of code you need in order to access your data so that you actually see and interact with that data on a webpage as a client or user. First things first though, you need the data. Where would one get data? Well, we're starting simple, so let's just say that we have data that's all ready to be used in whatever code editor you use. You can access that file locally as db.json(or whatever you want to call that JSON file). This would be the easiest way. That file could look something like this and should be in JSON syntax.

[
{
    "name": "John",
     "age": 22,
    "gender": "male",
},
{
    "name": "Susie",
    "age": "20",
     "gender": "female"
}
]
Enter fullscreen mode Exit fullscreen mode

For more information on JSON take a look here for a simplified explanation with some examples. On to the next!

Now, you've got your file and you're ready to start accessing this data and plugging it in on the interweb. How would you do that? Well, with fetch! We're gonna tell JavaScript to go and "fetch" our stuff that we want to use. We'll do so with this:

fetch()

Within the parentheses, or the parameters, we would put in the file or the URL of the server where our data currently lives. In this case, we're just going to fetch the JSON file. Don't forget to include quotation marks, doesn't matter if they're double or single, as that file or URL needs to be a string. I know it's silly to mention, but it's those little mistakes that tend to have you pulling out your hair when you're trying to get your code to work so just keep it in the back of your mind.

fetch('dummy.json')

This is also called a GET request. You don't need any other configuration in order to make this a GET request. See? Simple! You can also use POST, PATCH, or DELETE with some configuration with this first line, but let's just focus on our GET request for now.

Well, we fetched our data, now what do we do? We're now going to request a response by chaining a method onto fetch called .then. You can also do this with async/await, but we're only focusing on the .then method.

With the .then() we're going to request a response from the server to parse our stream of data and send us something in return while we wait. We know that our data is JSON so let's use another simplified method (arrow function) to get that response and use the .json() method to return a promise for us. We have to return the data from the callback function in order to use the data in the next .then() method call.

fetch('dummy.json')`
.then(response => response.json())`
Enter fullscreen mode Exit fullscreen mode

Don’t forget to console log to make sure your data is being captured with this:

.then(response => console.log(response))
Enter fullscreen mode Exit fullscreen mode

Remember to add the .json() as just console logging it isn't really doing anything with the data yet. We still need it to be in object format so remove the console.log after you've confirmed it works.

Pizza Analogy

Okay, so now that we're politely telling JavaScript to give us a response it's going to take some time doing so, but luckily for us, it's asynchronous which means it will run all our other lines of codes first and then come in when it's ready with our data. Remember when I mentioned that fetch is actually "promised based"? Well let me explain that a little further here.

I heard an amazing analogy from a video I watched during my course that I hope provides a better understanding of how fetch works. Imagine that you're ordering pizza from your favorite pizza place. You order from your phone, and that order (fetch request) gets sent to the pizza company (the server) who then send you a receipt (the response/promise) of when your order will arrive. But it takes some time for that pizza to get to you as it needs to be driven and delivered to you. You don't sit there and watch the clock, you're more than likely watching tv and doing other things while you wait for your pizza (asynchronous JS). When your pizza arrives it comes in a box (.json) that then needs to be opened in order for you to eat it.

The Final Act

Alright, this next part gets a little tricky. So the data is being fetched and we're requesting promises for the data to be sent back to us when the data is ready. But we want to do something with that data once it's been translated for us. That's where the second promise comes in, another .then(). This .then is the one that does all the heavy lifting. But first! Console log it! Like so:

.then(data => console.log(data))

From here you can then customize how you want the data to be retrieved and how it sums up on the page, whether you're iterating over an array of data from your JSON file, or from an external API, creating new elements to append images to, or creating event listeners to enhance user interaction on your app or webpage. Hopefully, this understanding will help you get started.

Resources:
Using Fetch API
JSON
GET Requests
Working With Data & APIs in JavaScript

Top comments (0)