0

I have been searching for hours to make a javascript variable that holds that data from an imported JSON object. I can't find anything that comes close to helping me figure it out. Every time I search this topic it just brings me to tutorials on how to initiate a JSON file in js for external use. I am trying to use the variable with the JSON object with D3.js. This is the basic code from my last attempt:

const dataset =
  document.addEventListener('DOMContentLoaded', function(){
    fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
      .then(response => response.json())
      .then(data => data.data);
  });
console.log(dataset);

I know that I can put the console.log within the fetch().then() method, but in order to use it with D3.js the way I want to it needs to be a global variable. I have tried to initialize the variable within the fetch() method, but that doesn't allow me to use it globally. I have also tried this sort of code:

var dataset = [];
  document.addEventListener('DOMContentLoaded', function(){
    fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
      .then(response => response.json())
      .then(data => dataset = data.data);
  });
console.log(dataset);

As you might expect the dataset remains an empty array.

---Update---
Here is the codepen project: https://codepen.io/critchey/pen/YzEXPrP?editors=0010

  • use setIterval and check 'dataset' until it has values, But I am sure there is way in d3js to call its method from .then to load data – Mohammed Raja Jan 27 '22 at 19:45
  • The "dataset remains an empty array" because you're logging it before it's been populated with data. Your call to console.log happens before fetch/then happens. – jarmod Jan 27 '22 at 19:45

1 Answers1

1

This one should work:

const dataset = await fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
  .then(response => response.json())
  .then(data => data.data);

The other way is:

let dataset;
fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
  .then(response => response.json())
  .then(data => dataset = data.data);

but value of dataset will be no available just after this code, but once Promise is resolved. So again you should add await before fetch to wait for Promise.

fela
  • 679
  • 8
  • 7
  • That did it! Thanks! I used `await` and got a warning saying that `await` can only be used within an `async` function. So I worked it for a bit and came up with this: ` async function imprt() { const dataset = await fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json') .then(response => response.json()) .then(data => data.data); return dataset; } const dataset = imprt(); console.log(dataset) ` Thanks, this helped a lot. I wasn't familur with await. – Clayton Ritchey Jan 27 '22 at 22:35
  • Here is the codepen to make it easier: https://codepen.io/critchey/pen/YzEXPrP?editors=0010. Actually, I still have a problem. That code comes back as as `Promise {}[[Prototype]]: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: Array(275)` As you can see it returns the state of the Promise... over time I think... then it finally returns the result.. It is really confusing. When I call `console.log(dataset)` within the function it shows in the console as the object I am looking for. But if I have the console.log out of the function it shows it only in the format above. – Clayton Ritchey Jan 27 '22 at 23:19
  • Nów I can see what are you trying to achieve. Generally you are not able to run await in the root of script - only async functions can do that until it is module. How do you run this script? Is it command line? if yes then rename it to .mjs and you can run it with `node script.mjs`. In this way you can run your async function with await: const datset = await imprt(); in the root of the script. Or const dataset = await fetch(...). – fela Jan 27 '22 at 23:57
  • I eventually just added the D3.js within the `async` function. I didn't want to go that route, but it seems to be the most commonly used method that I can find. – Clayton Ritchey Jan 31 '22 at 16:26