Search code examples
javascriptgoogle-drive-api

Javascript Drive API nextPageToken never changes


I am trying to build a Chrome Extension using the Drive API. I believe I have it working mostly but I keep getting the same nextPageToken on recursive calls. I want to be able to list all the file's ids by checking if nextPageToken exists after each fetch.

I am doing a simple version of it initially by using a counter (ctr) in a do loop. The returned data from the fetch always has the same nextPageToken value, per the last 2 lines of code below.

let morePagesAvailable = '';
let initVal; //oauth2 initialization
let url = new URL('https://www.googleapis.com/drive/v3/files?fields=nextPageToken,files(id)&pageToken=');
let params = url.searchParams;

//onLoad
window.onload = function () {
      document.querySelector('button').addEventListener('click', function () {
            chrome.identity.getAuthToken({ interactive: true }, function (token) {
                  init = {
                        method: 'GET',
                        async: true,
                        headers: {
                              Authorization: 'Bearer ' + token,
                              'Content-Type': 'application/json'
                        },
                        'contentType': 'json'
                  };
                  fetchIt(init);
            });
      })
};

//Fetch data
async function fetchIt(initVal) {
      let ctr = 1;
      do {
            params.delete('pageToken');
            params.append('pageToken', morePagesAvailable);
            console.log(url.toString());
            console.log(morePagesAvailable);
            try {
                  const response = await fetch(
                        url.toString(),
                        initVal)
                  const data = await response.json();
                  console.log(data);
                  addData(data);
            } catch (error) {
                  console.error(error);
            }
            ctr++;
      } while (ctr < 4)
}

// data => object
function addData(object) {
      data.push(object);
      morePagesAvailable = data[0].nextPageToken.toString();
      console.log(morePagesAvailable);   // working: but always the same string     
      console.log(data[0].files[1].id);  // working: but always the same string
}

Solution

  • The code works fine. I didn't realize that the nextPageToken for each successive call is the same as the last call ie. when you loop through the fetching of data, nextPageToken stays the same; it only becomes nil on the last fetch.