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
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.