My function works for the first call only; meaning I only get 50 video IDs and then it throw a lot of errors (400 error). And then when I use the nextPageToken, it doesn’t work. I believe it’s because I’m calling the API inside a while loop!
Here’s my current code:
const DEFAULT_UPLOADS_ID = 'UUJQJAI7IjbLcpsjWdSzYz0Q'
async function getPlaylistItemsById(id = DEFAULT_UPLOADS_ID) {
const YOUTUBE_CHANNEL_UPLOADS = [];
try {
const request = await gapi.client.youtube.playlistItems.list({
part: ["snippet, contentDetails"],
maxResults: 50,
playlistId: id,
});
const response = await request.result;
for (const item of response.items) {
YOUTUBE_CHANNEL_UPLOADS.push(item.contentDetails.videoId);
}
let nextPageToken = response?.nextPageToken;
while (nextPageToken !== undefined) {
await gapi.client.youtube.playlistItems
.list({
part: ["snippet, contentDetails"],
maxResults: 50,
nextToken: nextPageToken,
})
.then((response) => {
for (const item of response.items) {
YOUTUBE_CHANNEL_UPLOADS.push(item.contentDetails.videoId);
}
})
.catch((error) => {
console.log("Something went wrong with getPlaylistItems(): ", error);
});
}
return YOUTUBE_CHANNEL_UPLOADS;
} catch (error) {
console.log(error);
}
}