This console.log will be called before the fetch has added anything to your variable, that is why it will show as empty, try like this instead…
let dataset = {};
fetch("https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json")
.then(response => response.json()) //converts request from fetch to json
.then(data => {
dataset = JSON.stringify(data["data"]);
}).then(() => {
console.log(dataset);
})
or a better way to do it is just have all your code run in an init function with your data …
const url = "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json"
window.onload = async () => {
const response = await fetch(url)
const data = await response.json()
//initilize with data
init(data)
}
function init({ data }) {
console.log(data)
//run your code here and with data
}
Hey @biscuitmanz, thanks for the help. This asynchronous method with the init function looks like a good way to obtain the data without running into this issue. The fetch method is what FCC taught me though, and I want to try and understand this error.
Forgetting the console.log, I just want to take the data from the API and assign it to the dataset variable so I can work with it outside of the then() statements. How can I do this with the fetch method?
your still going to have you code in callback function so it doesn’t run until you have received the fetch data so like this.
let dataset = {};
fetch("https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json")
.then(response => response.json()) //converts request from fetch to json
.then(data => {
dataset = JSON.stringify(data["data"]);
init()
});
function init() {
console.log(dataset);
// code goes here
}
if you run this code below you will see why dataset shows empty when console.log it
let dataset = {};
console.log(1) // first
fetch("https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json")
.then(response => response.json()) //converts request from fetch to json
.then(data => {
dataset = JSON.stringify(data["data"]);
console.log(2) // third
});
console.log(3)// second
console.log(dataset)