0

I am tring to store the data from the novelcovid api call "api.countries({country:"USA"}).then(console.log)" into the index_data object. I am using the function getData to store the values into the index_data object. The issue I am having is that the index_data object will not update outside of the scope of the getData() function, I want to be able to globally access the new properties assigned to the object. Any ideas on how I can solve this will be much appreciated.


let totalConfirmed; 
                                          
let index_data = {
  totalConfirmedCases: null,
  totalConfirmedDeaths: null,
  totalRecovered: null,
  casesToday: null
};

api.countries({country:"USA"}).then(totalData);

function totalData(result) {
  totalConfirmed = result.cases; 
  getData(index_data, totalConfirmed);  
};

function getData(theObject, tcVar){
  theObject.totalConfirmedCases = tcVar;
}; 

console.log(index_data);

Cian
  • 1
  • "*[...] the index_data object will not update outside of the scope of the getData() function*"–Yes it will, but only after you are logging its value. "*[...] globally access the new properties assigned to the object*"–You will need to store the resulting promise and use `promise.then(index_data => /**/)` or use `async`/`await`. – str Aug 17 '20 at 17:41

1 Answers1

0

Objects are (effectively) passed by reference in js. The problem is not with the object, it is with when you are logging to the console. Since you are making an asynchronous api request, you should console log after getData is called.

As str suggested in his comment, you can use async await to do this easily.

Nate Levin
  • 918
  • 9
  • 22