Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get fetch result from API to store as a global variable? [duplicate]

I am working on a project where I pull an API of US GDP and then create a graph from the data. Right now I'm hung up on the first part of the problem in that I am struggling to get the JSON to store in a variable so I can work with it in the rest of my project. I've looked at a few other threads and haven't gotten a solution to work for me.

Below is my current code.

let jsondata =;

fetch('https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json').then(
    function(u){ return u.json();}
  ).then(
    function(json){
        jsondata = json;
        console.log(jsondata)
    }
  )


console.log(jsondata)

Currently, I can console.log(json) and console.log(jsondata) within my second function. However, even though I've declared the variable outside of the function, it doesn't make the variable its self global. What am I missing?

like image 540
David Reke Avatar asked Jan 26 '23 03:01

David Reke


1 Answers

fetch is an asynchronous function. That means when the function is called, it is added to an event-loop and the code will continue. When it reaches your last line the jsondata variable will not yet be filled since the fetch function hasn't completed yet.

You should add an await in front of you function to make sure it is finished before the code will continue. For examples, see: https://dev.to/shoupn/javascript-fetch-api-and-using-asyncawait-47mp

let jsondata = "";
let apiUrl = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json"

async function getJson(url) {
    let response = await fetch(url);
    let data = await response.json()
    return data;
}

async function main() {
    //OPTION 1
    getJson(apiUrl)
        .then(data => console.log(data));

    //OPTION 2
    jsondata = await getJson(apiUrl)
    console.log(jsondata);
}

main();
like image 114
ToTheMax Avatar answered Jan 29 '23 21:01

ToTheMax