I'm trying to get all 137 videos from a Youtube playlist with the following code:
function loadVideos() {
let pagetoken = '';
let resultCount = 0;
const mykey = "***********************************";
const playListID = "PLzMXToX8Kzqggrhr-v0aWQA2g8pzWLBrR";
const URL = `https://www.googleapis.com/youtube/v3/playlistItems?
part=snippet
&maxResults=50
&playlistId=${playListID}
&key=${mykey}`;
fetch(URL)
.then(response => {
return response.json();
})
.then(function(response) {
resultCount = response.pageInfo.totalResults;
console.log("ResultCount: " + resultCount);
pagetoken = response.nextPageToken;
console.log("PageToken: " + pagetoken);
resultCount = resultCount - 50;
console.log("ResultCount: " + resultCount);
while (resultCount > 0) {
const URL = `https://www.googleapis.com/youtube/v3/playlistItems?
part=snippet
&maxResults=50
&playlistId=${playListID}
&key=${mykey}
&pageToken=${pagetoken}`;
fetch(URL)
.then(response => {
return response.json();
})
.then(function(response) {
pagetoken = response.nextPageToken ? response.nextPageToken : null;
console.log("PageToken: " + pagetoken);
});
resultCount = resultCount - 50;
}
})
.catch(function(error) {
console.log("Looks like there was a problem: \n", error);
});
} // End of loadVideos function
// Invoking the loadVideos function
loadVideos();
The first 50 videos get loaded The second 50 videos get loaded too But instead of loading the remaining 37 videos from the list, my script loads the previous 50 videos again.
It seems that the pagetoken doesn't get updated for the third request.
What is wrong with my code?