Can't write d3.json arrays to html properly

Hi,

Having some issue writing d3 arrays to html paragraph.
How should I write it so that it is correctly understood by the browser.

<!DOCTYPE html>
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>
</head>
<body>  
  <p id="b"></p>
  <p id="c"></p>
  <p id="theData"></p>
</body>
<script>
  var theData, b, c = [[1, 2, 3],["L"]];
  var d = d3.json(
    "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json"
  ).then((d) => {
    theData = d.data;
    b = [[1, 2], [2, 3]];
    console.log(theData[0]);
    console.log(b[0]);
  })
  document.getElementById("c").innerHTML = "Print 'c' value must be first: " + c;
  document.getElementById("b").innerHTML = "Print 'b' value mut be second : " + b;
  document.getElementById("theData").innerHTML = "Try print 'theData' one of two demession array:" + theData[0];
</script>
</html>

Hello, more information please, can you post a link to the challenge and/or project. I would say just from looking at your html that JS should be in the body and why do you have this script src = code in the head where are the other requirments. Are you trying to do all this form the dev tools environment?

It is async code, theData is undefined when the execution reaches the DOM code. You can put the DOM code inside the then block to have access to the data.


let initialData = "Initial value";

fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then((response) => response.json())
  .then((json) => {
    initialData = json;
    console.log(json); // todo object
  });

console.log(initialData); // "Initial value"

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.