React JS and Google Spreadsheets: Cannot Read Property '2' of Null

Viewed 1467

I'm currently working with React JS and Google Spreadsheets and am following something similar to this article. However, I'm running into a problem. Whenever I try to connect to my spreadsheet, my React app runs successfully for a few seconds and then crashes, with this error message: enter image description here

Currently, this is my code:

import {
  GoogleSpreadsheet
} from 'google-spreadsheet';

function App() {
  const setup = async () => {
    const doc = new GoogleSpreadsheet('my spreadsheet-id'); // Obviously putting in my real spreadsheet id and data instead of this in my real code
    await doc.useServiceAccountAuth({
      client_email: 'my client-email',
      private_key: 'my private-key'
    });

    await doc.loadInfo(); // loads document properties and worksheets

    const sheet = doc.sheetsByIndex[0]; // or use doc.sheetsById[id]
    console.log(sheet.title);
    console.log(sheet.rowCount);
  }

My app function does have a render method and I do eventually run the setup function to connect to my spreadsheet.

Does anyone know why this is happening and how I can fix it? Thanks!

5 Answers

I figured this out after a while... To those who found this StackOverflow thread as their only hope, I'll leave this answer here to save some of your hours.

Apparently, if you are storing the private token inside your .env, the \n character will be parsed in as \\n. You would need to make sure that the slashes are NOT escaped.

For my project, this is the solution:

await doc.useServiceAccountAuth({
  client_email: 'my client-email',
  private_key: process.env.REACT_APP_SHEET_PRIVATE_KEY.replace(/\\n/g, '\n')
});

Make sure you have turned on your api library as it gives the same error when api that you use is turned off.

For me, the issue was also with the API key. I was under the impression that I was supposed to delete the part which said "Begin Private Key...". People having this issue should check their API keys.

I've encoded the private key in base64, then pasted it in .env

Then put in my code:

const private_key = Buffer.from(GOOGLE_SA_PRIVATE_KEY, 'base64').toString('utf8')

const doc = new GoogleSpreadsheet(SPREADSHEET_ID)

doc.useServiceAccountAuth({
  // env var values are copied from service account credentials generated by google
  // see "Authentication" section in docs for more info
  client_email: GOOGLE_SA_EMAIL,
  private_key: private_key.replace(/\\n/g, '\n'),
})
Related