0

I am working with an api in javascript to return some healthcare data to be analyzed and visualized. I created a function get_data() to access the data so it can be used elsewhere in the script:

function get_data() {
console.log(vaccination_data[0]);
var vax_data = vaccination_data[0];
console.log(vax_data.city)
return vax_data
}

This works well within the function and I can log the data and it's elements to console. The problem I'm having is when I try to assign the return variable vax_data to a variable outside the function with var data = get_data() I am getting the error:

"<a class='gotoLine' href='#60:22'>60:22</a> Uncaught TypeError: Cannot read properties of undefined (reading 'city')"

I have tested with a simple function and it works well, example:

function a() {
   var str = "first";
   return str
}

var string = a()

console.log(string)

Can anyone tell me why it works differently from the data that is being returned from the api?

Full code:

var vaccination_data = [];

$.ajax({
  url: "https://health.data.ny.gov/resource/nvtm-yit2.json",
  type: "GET",
  data: {
    "$limit" : 5000,
    "$$app_token" : 'aGFbKDOg0gCeCm2c9Od2EsFjL'
  }
}).done(function(api_data) {
    //console.log(api_data)
  vaccination_data = api_data;

    get_data();
});

function get_data() {
console.log(vaccination_data[0]);
var vax_data = vaccination_data[0];
console.log(vax_data.city)
return vax_data
}

var data = get_data()
console.log(data)

JSFiddle - https://jsfiddle.net/jconoranderson/v3aLx621/15/

John Conor
  • 722
  • 6
  • 20
  • 1
    You can only access the data after the ajax call has completed. For this reason, top-level code like `var data = get_data()` can't access the response. The standard dupe is https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – James Apr 17 '23 at 20:34
  • The problem with this standard close and link response I'm finding in javascript is that although this helps with my overall understanding of the language it doesn't quite address the specific problem I am facing... – John Conor Apr 17 '23 at 22:33
  • 1
    Put the code that operates on api_data into the .done function, or call other functions from within the .done function. You can't (ever) access api_data from top level code. Your example modified - https://jsfiddle.net/xymvwoqn/ – James Apr 17 '23 at 22:43
  • Thanks! What then if I wanted to use the data in another function elsewhere in the program? Is there a method to asynchronously pass that between 2 functions? I've added a function `use_data()` as an example - https://jsfiddle.net/jconoranderson/65y21g9p/6/ – John Conor Apr 18 '23 at 01:23
  • you pass in the data as a parameter instead of using a global variable. https://jsfiddle.net/1sf6bz53/1/ – James Apr 18 '23 at 01:29
  • Thank you @James, I appreciate you taking the time to genuinely help! I'll do my best to pay it forward. – John Conor Apr 18 '23 at 16:18

0 Answers0