9

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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
David Reke
  • 535
  • 1
  • 5
  • 20
  • 1
    The variable *is* global, you're just printing it before it gets assigned. – Bergi Apr 15 '20 at 12:31
  • Store the promise for the json data instead in the global variable, then wait for it each time you need the data. – Bergi Apr 15 '20 at 12:32

1 Answers1

15

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();
ToTheMax
  • 981
  • 8
  • 18
  • Thanks! I tried the following let jsondata; fetch('https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json').then( await function(u){ return u.json();} ).then( await function(json){ jsondata = json; console.log(jsondata) } ) console.log(jsondata) However I am now getting the error message "Uncaught SyntaxError: missing ) after argument list" That references my the line with my first await. Any thoughts? – David Reke Apr 15 '20 at 13:00
  • 1
    Check my updated answer – ToTheMax Apr 15 '20 at 13:31