I am working with youtube’s API and after it returns a data in JSON, I made a local variable with that JSON data.
Then I wanted to pass that local variable into the global scope.
I searched on stackoverflow and it says I should do something like this:
{window.localVariableName = localVariableName;}
console.log(localVariableName);
// this should give you the correct value
but in my app this does not work. I still get undefined on the console.
here’s my code
/*
TODO list
1. need a fetch function to handle HTTP request
2. renderMainVideo()
3. renderPlaylist()
4. call back function for the click event
*/
/*
Global variables and constants
*/
const key = 'my API key';
const playlistId = 'UUuSrv3qgQA7SSi6R9bWag5A';
var URL = 'https://www.googleapis.com/youtube/v3/playlistItems';
const options = {
playlistId: playlistId,
maxResults: 20,
key: key,
part: 'snippet'
};
/*
HTTP request
*/
URL += '?' + Object.keys(options).map((k) => k + '=' + encodeURIComponent(options[k])).join('&');
fetch(URL)
.then(res => res.json())
.then(function (data) {
var mainVideoID = data.items[0].snippet.resourceId.videoId;
// convert mainVideoID into a global variable
window.mainVideoID = mainVideoID;
console.log(data);
console.log(mainVideoID);
})
/*
Render main video
*/
//(this returns undefined)
console.log(mainVideoID);
how do I pass that mainVideoID into the global scope so I can use it in other places of my program?