Skip to content
Advertisement

HTML page is not showing the info I need from json file

My script, this should be showing the Name of game computers in html but it does not, I have been trying so much andI betit will just be something stupid that is wrong or missing Console says : TypeError: data is undefined

The console does show me retrieving the data works

"use strict";

window.addEventListener("load", Init);

function Init() {
  fetch("https://howest-gp-wfa.github.io/st-2021-1-S2-a-wfa-pe03-Jonas-Bundervoet/api/products.json")
  .then(function(response) { return response.json();  })
  .then(data => console.log(data))
  .then(function(data){
    tester(data)
  })
  .catch(err => console.log(err));

 window.addEventListener("load", tester);
}

My function to show data on screen (shows nothing)

function tester(data)
{
  let div = document.getElementById("test");

  for (var i = 0; i < data.length; i++) {
    let article = document.createElement("h1");
    article.innerHTML = 'Name: ' + data.GameComputers[0].Name;
    div.appendChild(article);
  };
}

In HTML I just have this in my body
<div id="test"></div>

Advertisement

Answer

console.log returns undefined

.then(data => console.log(data))
.then(function(data){
          tester(data)

Your first then returns the return value of console.log which is undefined.

So your second then recieves undefined as its data.

Don’t use multiple then callbacks here.

 .then(function(data){
           console.log(data)
           tester(data)

The JSON doesn’t consist of an array

The JSON you are looking at returns an object.

It doesn’t have a length.

for (var i = 0; i < data.length; i++) {

… is going to fail immediately.

You’ve got data.GameComputers[0] so I’m guessing you want to loop over GameComputers so:

  1. Check the length of that: i < data.GameComputers.length
  2. Make use of i when you read it: data.GameComputers[i].Name;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement