1

I'm trying to pull a random item from an array in a JSON file and then print this to a list in the DOM. I can get the item to successfully print to the console and even an alert but when it comes to putting it into the HTML it just comes up as undefined.

I've tried using fetch and .then functions which I didn't know anything about until this issue to try and ensure the data is retrieved before proceeding but this doesn't seem to make any difference.

const getJ = () => {
  fetch("https://api.myjson.com/bins/r8otf")
  .then(function(response) {
    return response.json(); 
  })
  .then(function(data) {
    let rIndex = Math.floor(Math.random()*data.list.length);
    console.log(data.list[rIndex]);
    return data.list[rIndex];
  })
};

const makeList = function () {
    const results = document.getElementById("resultBox");
    const list = document.createElement("ol")
    list.setAttribute("id", "list")
    const item = document.createElement("li")
    item.appendChild(document.createTextNode(getJ()));
    list.appendChild(item);
    results.appendChild(list);    
};

var btn = document.getElementById("mainButton");
btn.addEventListener("click", makeList);

I've set up a pen here to replicate the issue: https://codepen.io/mashw/pen/oKRZrV

What I want is what's printed to the console to appear in the list.

  • 1
    Basically: return the Promise (`return fetch()`) and handle the `.then()` stuff inside your makeList function. There is no way of returning from a `.then` callback. – MauriceNino Aug 12 '19 at 15:04
  • Thank you, I had to restructure a lot of my code into the .then functions but I got it working in the end. – Mash Williams Aug 13 '19 at 10:02

0 Answers0