Hafis Alrafi

Connect React App to Google Sheet API

2023-03-30

P.S. So far only working with NextJs (due to must be node/server side rendering capability)

  • Buka/signup google console https://console.cloud.google.com/
  • Create/select project
  • Search Google sheet API โ†’ Enable
  • Create service account
  • Create new key โ†’ json
  • Automatic downloaded json key โ†’ open it
  • Create file sheet in google drive
  • File โ†’ share โ†’ publish to web
  • Share โ†’ invite client_email yg ada di json file
  • install package npm i google-spreadsheet
  • pada page terkait, import package import { GoogleSpreadsheet } from "google-spreadsheet";
  • Create env
  • NEXT_PUBLIC_CLIENT_EMAIL=qwerty
    NEXT_PUBLIC_PRIVATE_KEY=abc
  • useEffect, ambil spreadsheet ID di gsheet
  • useEffect(async () => {
        const doc = new GoogleSpreadsheet(YOUR_SPREADSHEET_ID);
        await doc.useServiceAccountAuth({
          client_email: process.env.NEXT_PUBLIC_CLIENT_EMAIL,
          private_key: process.env.NEXT_PUBLIC_PRIVATE_KEY,
        });
        await doc.loadInfo(); // loads document properties and worksheets
        setDoc(doc);
    
    		// sheetId = 0, jika sheet id ada -> doc.sheetsById['sheetID']
        const sheet = doc.sheetsById[0];
    
    
        // read data
        const rows = await sheet.getRows();
        console.log(rows)
    }, []);
  • update data sheet
  • const updateRow = () => {
    	const sheet = doc.sheetsById[0];
    
        const row = {
          timestamp: timestamp(),
          name: name,
          wish: wish,
        };
    
        await sheet.addRow(row);
    }