JavaScript problem with Google Drive API file listing

I’m building a web application that aims to list files from Google Drive using JavaScript, but I’m encountering an issue. The error message indicates that the files property is undefined when I attempt to call the Drive API.

Here’s the code I’ve written so far:

var clientId = '123456789.apps.googleusercontent.com';
var apiKey = 'ABCDEFGHIJK';
var scopes = 'https://www.googleapis.com/auth/drive';

function initializeClient() {
    gapi.client.setApiKey(apiKey);
    window.setTimeout(checkAuthorization, 100);
}

function checkAuthorization() {
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthorizationResult);
}

function handleAuthorizationResult(authResult) {
    var loginButton = document.getElementById('login-btn');
    
    if (authResult && !authResult.error) {
        loginButton.style.display = 'none';
        executeDriveRequest();
    } else {
        loginButton.style.display = 'block';
        loginButton.onclick = initiateAuth;
    }
}

function initiateAuth(event) {
    gapi.auth.authorize({client_id: clientId, scope: [scopes], immediate: false}, handleAuthorizationResult);
    return false;
}

function executeDriveRequest() {
    gapi.client.load('drive', 'v2', makeDriveRequest);
}

function makeDriveRequest() {
    var request = gapi.client.drive.files.list({'maxResults': 10});
    
    request.execute(function(response) {
        for (var i = 0; i < response.items.length; i++) {
            var fileTitle = response.items[i].title;
            var modifiedDate = response.items[i].modifiedDate;
            var lastModifiedBy = response.items[i].lastModifyingUserName;
            
            var fileItem = document.createElement('div');
            fileItem.textContent = 'File Name: ' + fileTitle + ' | Last Modified: ' + modifiedDate + ' | Modified By: ' + lastModifiedBy;
            document.getElementById('file-list').appendChild(fileItem);
        }
    });
}

The error appears on the line: var request = gapi.client.drive.files.list({'maxResults': 10});

I’m getting this error: Uncaught TypeError: Cannot read property 'files' of undefined. What might be the reason for this issue? Is my method for loading the Drive API or the authentication process incorrect?

yep, looks like the gapi client isn’t fully loaded when you try to call it. make sure to check if it’s ready. also, since v2 is kinda old, switching to v3 could help you out a lot.

Your problem is that gapi.client.load runs asynchronously, but makeDriveRequest fires right away before the API finishes loading. You need proper error handling and to wait until the client’s actually ready before making requests. I hit this exact issue last year and fixed it by adding a callback verification step. Also heads up - Drive API v2 is deprecated and has been for a while. V3 has a completely different response structure and auth flow, but it’d actually solve these initialization headaches you’re dealing with. Quick fix for now: add a simple check to make sure gapi.client.drive exists before trying to access the files property.

Others mentioned timing, but there’s also a structural issue with your code. When you call gapi.client.load('drive', 'v2', makeDriveRequest), that third parameter is a callback that runs after the API loads successfully. Your current setup doesn’t handle loading failures though. I hit something similar building a document management system - adding a proper error callback helped me catch when the Drive API wasn’t loading right. Try wrapping your makeDriveRequest in a timeout or add some console logging to see if the load actually completes. That undefined error usually means the client object isn’t initialized yet, probably from network issues or auth problems your current error handling isn’t catching.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.