Having trouble saving JSON data to variable

Tell us what’s happening:
I can’t seem to be able to save JSON data to a variable after using the fetch method.

date1 variable is coming out as undefined, when I expect it to be “1947-01-01”

It seems like the dataset variable was never set to after the fetch method.

Your code so far

let dataset;

fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
    .then(response => response.json())
    .then((data) => {dataset = data.data});

const height = 520;
const width = 1060;
const pad = 20;

const date1 = dataset[0][0];

Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0.

Challenge: Visualize Data with a Bar Chart

Link to the challenge:

Hey @dvislearning Happy new year :partying_face:

I think the problem here is you are mixing up a bit async code with sync one, in fact, there is nothing that makes the script waiting until you fetch the data to execute the line const date1 = dataset[0][0];. try to treat the data1 variable as you did with the dataset one, for example, declaring it at the beginning to have it in the global scope and then assign the value into the second then you have.

Let me know if it doesn’t make sense.

Happy Coding :man_technologist:

dataset is undefined

let dataset;

fetch call is evaluated. The callback gets put in a queue, to be executed when possible

fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
    .then(response => response.json())
    .then((data) => {dataset = data.data});

You set some more variables

const height = 520;
const width = 1060;
const pad = 20;

dataset is currently undefined, so you attempt to access something on undefined (this is a runtime error, so the program will fall over at this point):

const date1 = dataset[0][0];

If the code could continue then at this point the callback for fetch will be evaluated.

JavaScript always executes things in order, but in this case you’ve got the order wrong – as @lucatardi says you’re mixing up async and sync code. The program doesn’t stop and wait until the value comes back before continuing unless you explicitly tell it to do that – it has to happen in the then

1 Like

@lucatardi and @DanCouper , thank you very much for your responses and happy new year!

It had not occurred to me that I was mixing up async and sync code. Initializing date1 as a global variable and then setting it inside one of .then did the trick. Thank you!


let dataset;
let date1;

fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
    .then(response => response.json())
    .then((data) => {
  dataset = data.data
  date1 = dataset[0][0];});