[SOLVED] rawg.io api call Javascript to display in html

Issue

This Content is from Stack Overflow. Question asked by Leigh Godson

I am still on a quest to figure out javascript and working with an API as part of a project I have been set (so still very new to this and only 2 weeks in to learning JS)

I have the API being called fine, I can see the output in network so I know I am getting a connection but despite looking around at ways to do this I am struggling to display the output in my html.

So I have to do this in vanilla js, using async with no .then chains etc.

The js I have so far:

      return (await fetch('https://api.rawg.io/api/games?key=CHANGED_FROM_MY_KEY')).json();
}

    document.addEventListener("DOMContentLoaded", async () => {
    let games = [];

      try {
            games = await fetchData();
        } catch (e) {
            console.log("Error!");
            console.log(e);
        }

        console.log(games);

      });

      function appendData(games){
            var mainContainer = document.getElementById("rawgGame");
            for (var i = 0; i < games.results; i++) {
                var div = document.createElement("div");
                div.innerHTML = 'gameName: ' + games.results[i].name;
                mainContainer.appendChild(div);
                div.innerHTML = 'gameImage: ' + games.results[i].background_image;
                mainContainer.appendChild(div);
                div.innerHTML = 'gameRating: ' + games.results[i].metacritic;
                mainContainer.appendChild(div);
              }
      }

      window.onload = function appendData() {
            console.log('The games will load now.');
        }

the output in console :

{count: 797560, next: "https://api.rawg.io/api/games?key=CHANGED_FROM_MY_KEY&page=2",…}
count
: 
797560
description
: 
""
filters
: 
{years: [{from: 2020, to: 2022, filter: "2020-01-01,2022-12-31", decade: 2020,…},…]}
next
: 
"https://api.rawg.io/api/games?key=CHANGED_FROM_MY_KEY&page=2"
nofollow
: 
false
nofollow_collections
: 
["stores"]
noindex
: 
false
previous
: 
null
results
: 
[,…]
0
: 
{id: 3498, slug: "grand-theft-auto-v", name: "Grand Theft Auto V", released: "2013-09-17", tba: false,…}
1
: 
{id: 3328, slug: "the-witcher-3-wild-hunt", name: "The Witcher 3: Wild Hunt", released: "2015-05-18",…}
2
: 
{id: 4200, slug: "portal-2", name: "Portal 2", released: "2011-04-18", tba: false,…}
3
: 
{id: 5286, slug: "tomb-raider", name: "Tomb Raider (2013)", released: "2013-03-05", tba: false,…}
4
: 
{id: 4291, slug: "counter-strike-global-offensive", name: "Counter-Strike: Global Offensive",…}
5
: 
{id: 5679, slug: "the-elder-scrolls-v-skyrim", name: "The Elder Scrolls V: Skyrim",…}
6
: 
{id: 12020, slug: "left-4-dead-2", name: "Left 4 Dead 2", released: "2009-11-17", tba: false,…}
7
: 
{id: 13536, slug: "portal", name: "Portal", released: "2007-10-09", tba: false,…}
8
: 
{id: 4062, slug: "bioshock-infinite", name: "BioShock Infinite", released: "2013-03-26", tba: false,…}
9
: 
{id: 3439, slug: "life-is-strange-episode-1-2", name: "Life is Strange", released: "2015-01-29",…}
10
: 
{id: 802, slug: "borderlands-2", name: "Borderlands 2", released: "2012-09-18", tba: false,…}
11
: 
{id: 28, slug: "red-dead-redemption-2", name: "Red Dead Redemption 2", released: "2018-10-26",…}
12
: 
{id: 13537, slug: "half-life-2", name: "Half-Life 2", released: "2004-11-16", tba: false,…}
13
: 
{id: 4286, slug: "bioshock", name: "BioShock", released: "2007-08-21", tba: false,…}
14
: 
{id: 1030, slug: "limbo", name: "Limbo", released: "2010-07-21", tba: false,…}
15
: 
{id: 2454, slug: "doom", name: "DOOM (2016)", released: "2016-05-13", tba: false,…}
16
: 
{id: 3070, slug: "fallout-4", name: "Fallout 4", released: "2015-11-09", tba: false,…}
17
: 
{id: 32, slug: "destiny-2", name: "Destiny 2", released: "2017-09-06", tba: false,…}
18
: 
{id: 58175, slug: "god-of-war-2", name: "God of War", released: "2018-04-20", tba: false,…}
19
: 
{id: 11859, slug: "team-fortress-2", name: "Team Fortress 2", released: "2007-10-10", tba: false,…}
seo_description
: 
""
seo_h1
: 
"All Games"
seo_keywords
: 
""
seo_title
: 
"All Games"

My thinking (again, very new to this so I am only just getting a grasp of how to work with JS) is that my first function is requesting the api json and logging errors or displaying the json. The the second function is taking that data and appending it into my html but breaking down the individual sections I want to display in their own child div so I can style them later.

I’m sure there’s a much easier and more elegant way to do this but even this method doesn’t seem to put anything into my html. Clearly I am doing something wrong but can’t figure out what.

For some reason I just seem to keep hitting a wall with JS, I can look at functions and figure out what they do a little at least, but something with fetch is just not making it much further than my eyes and sinking in.

I am seeing the console.log of The Games will load now and none of the code is showing an error so my guess is how I am trying to specify and display the different fields is wrong.

thanks



Solution

You need to create multiple div elements.

                var div
                div = document.createElement("div");
                div.innerHTML = 'gameName: ' + games.results[i].name;
                mainContainer.appendChild(div);

                div = document.createElement("div");                            
                div.innerHTML = 'gameImage: ' + games.results[i].background_image;
                mainContainer.appendChild(div);

                div = document.createElement("div");
                div.innerHTML = 'gameRating: ' + games.results[i].metacritic;
                mainContainer.appendChild(div);
              }

You may want to consider creating a parent div, and then add child div to it, so you can style the parent container.

Also use innerText instead of innerHTML, as you are adding text, not html text.

div.innerText = 'gameName: ' + games.results[i].name;

Finally, you need to call your append data function on load.

function appendData(
  // code here
}

window.onload = () => {
    console.log('The games will load now.');
    appendData(games)
}

One more issue is the case where onLoad is called before your async data call resolves. In that case, games will not be set. A workaround might be to 1. bootstrap the whole data call to start inside of onLoad, or 2. Check for loaded after games is resolved.


This Question was asked in StackOverflow by Leigh Godson and Answered by Steven Spungin It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?