DEV Community

Cover image for JavaScript Is Not a Dog. Controlling Fetch is Vital to functionality.
K Montgomery
K Montgomery

Posted on

JavaScript Is Not a Dog. Controlling Fetch is Vital to functionality.

Controlling fetch is often something that we as beginner devs don't even realize we need to do. When I first began learning about fetch we were just told it's a function and initially, myself and some cohort-mates assumed you could call it anywhere and without any context... to which we quicky learned that calling fetch all willy-nilly is not only a bad idea but can also cause you to lose control of your fetched API's.

What do I mean by this? If you make a fetch request inside of another function, you will be able to attach it to variables and call it back later on in your code instead of just having the API data floating around with no where to go.

I, unfortunately, learned this lesson the hard way. The first time experiencing a code challenge in school I panicked and forgot to nest my fetch request and ended up in tears over being unable to call the data. Don't be like me. A really good method I have found for embedding your fetch call in order to make it more accessible it is:
document.addEventListener('DOMContentLoaded', () => {
fetch('http://localhost:3000/')
.then(resp => resp.json())
.then(data => renderAll(data))
});

Now what does this function do?

Line 1: the jest of it is that it is setting up for the data to be called and immediately rendered in to the DOM.

Line 2: this is the actual fetch command. You use an API URL and pull the data within it in to your terminal

Line 3: creating the response in .json and activating that command with the ()

Line 4: I just used generic variables in this example, however, whatever you use in place of "data" and "renderAll" can and SHOULD BE called again in order to access the internal data and have it appear in your webpage.

You cannot do any of these without the other. They live in blissful harmony together to make your life easier. Trust me on this one. Coding is so full of tears there's no point in making it harder than it needs to be.

Top comments (1)

Collapse
 
tzwel profile image
tzwel

I don't see the point of this article. Does it just tell us that fetch has to be inside await? A quick glance at the console will tell you exactly that. Care to explain?