Problems with Using Fetch API

So here’s the code snippet I’m having issues with:

let dataSet;

const storeJSON = (data) => {
    dataSet = data;
}

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

console.log(dataSet);

So what I am trying to do is basically store the json that I get from the provided url into the global variable dataSet. Now the problem is the console.log() method at the end of this snippet tells me that dataSet is undefined. And it doesn’t matter if I store the returned json directly into the variable or via storeJSON(). In both times console.log() returns undefined. Why is that ? When I call console.log() from within storeJSON() I get the json printed to the console.

From your snippet, what purpose does the below function serve?

const storeJSON = (data) => {
    dataSet = data;
}

for your problem, check what order things are happening by putting a console log in your fetch and see which console log entry comes first. I don’t know how you’re calling the fetch based on the code you provided

1 Like

That’s because the console.log is executed before the fetch has completed and thus dataSet hasn’t been set to data when the console.log does its thing. Remember, fetch is asynchronous, so you can’t count on it being completed before you get to the console.log. If you want to log the value of dataSet after the fetch has completed you need to do it in the then callback where you are setting its value.

2 Likes

This is by the asynchronous process. The console.log is executed before the fetch finish his job. You can print the data after the finished fetch.

fetch("https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json")
    .then(response => response.json())
    .then(data => {
      storeJSON(data);
      console.log(dataSet);
});

You can learn more about Async/Await here

1 Like

Sorry for the late reply. Okay so how would I make sure that the rest of my code gets executed after the fetch part has been executed successfully ?

So should should I basically nest all the code that’s messing with the dataset within my 2nd then callback ?

Hey that’s just a function that I executed within the 2nd then.() callback. I was trying to see if storing the dataset with a function would do me any favor. Sorry for the late reply.

Yes. I would suggest you create a separate function to do this and pass data into that function.

1 Like

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