Fetching and Displaying Data using the Fetch API

Blendi Ibraj
3 min readFeb 5, 2021

--

Fetching data and displaying it in the browser can be a great exercise to practice your front-end skills. In this article, you’ll see examples of the Fetch API, template literals, and JavaScript’s .forEach() function. We’ll be using the SpaceFlightNewsApi to fetch some articles on the latest news in space.

The code we’ll need:

In the HTML, we have a semantic <section> tag with an <h2> for our title and a <div> with an id of “articles-container” which will house all of our fetched articles.

Our fetch call on line 12 takes one argument, the path to the resource from which we’re trying to obtain info. The exact type of info is a JSON file. However, we are first given a Promise, which is an object that represents an action the may be completed or fail in the future. Our .then() chaining is essentially saying, “if this promise resolves, do this with the response.”

The first object we’re given if the Promise does indeed resolve, is an HTTP response which we must convert into JSON using the .json() method (line 13).

On our next .then() call (line 14), we can now manipulate the JSON object we’ve been trying to obtain. So, we grab our “articles-container” <div> and begin to inject the info from the API as HTML using the .forEach() method (line 16).

For reference, here’s what the DOM looks like now that we’ve utilized our API info. I’ve expanded one of the article items to expose the detail and left the others collapsed below it:

The Fetch API and promises can be a lot to digest when first learning how to use them. You can practice by simply creating a file and trying to output API info in the browser until you get it right!

You can see how I’ve styled this info in my project, SpaceLog, below:

Take a look at the well-organized SpaceFlightNewsAPI:

https://github.com/spaceflightnewsapi/spaceflightnewsapi

As always, if you need more in-depth information about this concept, check out the documentation here:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Blendi Ibraj
Blendi Ibraj

Written by Blendi Ibraj

0 Followers

I'm a front-end developer based in NYC

No responses yet

Write a response