I used Google Sheets to create a simple database which i want to manipulate with tabletop.js to build a random quote generator. I can’t figure out how to save the data I pull through to a global variable so I can run the rest of my code.
My suspicion is that it has to do with the data loading time. When i attempt to log the data outside the getData()
function I get undefined
. However, when I log the data both inside the getData()
function and the setTimeout()
function the data appears in my console.
Since tabletop.js isn’t a regular API do you know how I can check that my data has been stored to a global variable and then run the rest of my code?
Thank you very much
//key
const tableTopKey = 'myKey';
//request data from spreadsheet
setup = () => {
Tabletop.init(
{ key: tableTopKey,
callback: getData,
simpleSheet: true
});
}
//initialize on page load
window.addEventListener('load', setup);
//create global variable to store data
let myData;
//store data in variable
getData=(data, tableTop)=>{
myData = data;
console.log(`Logging data inside the getData function ${myData}`);
}
//log data outside the getData function
console.log(`Logging data outside the getData function ${myData}`);
//log data with delay outside the function
setTimeout(function(){
console.log(`Logging data with 1,5 sec delay ${myData}`);
},1500)