npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@nuuruuur/react-appscript-db

v0.1.2

Published

Framework-agnostic hooks for Google Apps Script Web Apps backed by Google Sheets

Downloads

203

Readme

react-appscript-db

Bahasa Indonesia | English

npm version license


Apa Itu Package Ini?

Bayangkan kamu punya database gratis dari Google (Google Sheets), tapi susah diakses dari website. Package ini membantu website kamu berkomunikasi dengan Google Sheets.

┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
│   Website Kamu  │ ──▶ │  Google Apps    │ ──▶ │  Google Sheets  │
│   (React/Vue)   │ ◀── │    Script       │ ◀── │   (Database)    │
└─────────────────┘     └─────────────────┘     └─────────────────┘

Yang kamu dapat:

  • Database gratis (Google Sheets)
  • Tidak perlu server berbayar
  • Cocok untuk belajar, tugas, portofolio, atau MVP

Daftar Isi

  1. Persiapan
  2. Instalasi
  3. Setup Google Sheets
  4. Setup Google Apps Script
  5. Gunakan di React
  6. Gunakan di Vanilla JS
  7. Contoh Lengkap
  8. Troubleshooting
  9. FAQ
  10. Glossary

Persiapan

Sebelum mulai, pastikan kamu sudah punya:

  • [ ] Node.js (versi 18 atau lebih baru) - Download di sini
  • [ ] Akun Google - untuk Google Sheets dan Apps Script
  • [ ] Code editor - VS Code atau yang lainnya
  • [ ] Dasar HTML/CSS/JS - sudah bisa membuat website sederhana

Instalasi

Untuk React (dengan TanStack Query)

Buka terminal di folder project kamu, lalu ketik:

npm install react-appscript-db @tanstack/react-query

Untuk Vanilla JS (tanpa React)

npm install react-appscript-db

Setup Google Sheets

Langkah 1: Buat Spreadsheet Baru

  1. Buka Google Sheets
  2. Klik Blank atau Spreadsheet Kosong
  3. Beri nama file, misal: DatabaseWebsite

Langkah 2: Buat Tabel

Buat kolom seperti ini:

| id | nama | email | umur | |----|------|-------|------| | 1 | Budi | [email protected] | 25 | | 2 | Sari | [email protected] | 22 |

Tips:

  • Baris pertama adalah header (judul kolom)
  • Mulai data dari baris ke-2

Langkah 3: Salin URL Spreadsheet

  1. Klik Share (Bagikan) di pojok kanan atas
  2. Klik Change to anyone with the link (Ubah ke siapa saja dengan link)
  3. Pilih Viewer (Pengakses lihat saja)
  4. Salin link-nya, simpan dulu nanti dipakai

Setup Google Apps Script

Langkah 1: Buka Apps Script

  1. Buka script.google.com
  2. Klik New Project (Proyek Baru)

Langkah 2: Salin Kode

Hapus semua kode yang ada, lalu salin kode ini:

function doGet(e) {
  const action = e.parameter.action || 'default';
  const params = e.parameter;
  
  return ContentService
    .createTextOutput(JSON.stringify(handleAction(action, params)))
    .setMimeType(ContentService.MimeType.JSON);
}

function doPost(e) {
  const body = JSON.parse(e.postData.contents);
  const { action, params = {} } = body;
  
  return ContentService
    .createTextOutput(JSON.stringify(handleAction(action, params)))
    .setMimeType(ContentService.MimeType.JSON);
}

function handleAction(action, params) {
  try {
    let data;
    
    switch (action) {
      case 'getData':
        data = getData(params);
        break;
      case 'insertRow':
        data = insertRow(params);
        break;
      case 'updateRow':
        data = updateRow(params);
        break;
      case 'deleteRow':
        data = deleteRow(params);
        break;
      default:
        return { success: false, error: 'Unknown action: ' + action };
    }
    
    return { success: true, data };
  } catch (err) {
    return { success: false, error: err.toString() };
  }
}

function getData(params) {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const data = sheet.getDataRange().getValues();
  return data;
}

function insertRow(params) {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const { values } = params;
  sheet.appendRow(values);
  return { inserted: true };
}

function updateRow(params) {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const { row, values } = params;
  for (let i = 0; i < values.length; i++) {
    sheet.getRange(row, i + 1).setValue(values[i]);
  }
  return { updated: true };
}

function deleteRow(params) {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const { row } = params;
  sheet.deleteRow(row);
  return { deleted: true };
}

Langkah 3: Hubungkan ke Spreadsheet

  1. Klik ikon Project Settings (gear icon) di sidebar kiri
  2. Cari Google Sheets Project ID
  3. Kembali ke Google Sheets, lihat URL-nya:
    https://docs.google.com/spreadsheets/d/[BAGIAN_INI]/edit
  4. Salin bagian yang ditandai, paste ke Google Sheets Project ID
  5. Klik Set Project ID (Simpan)

Langkah 4: Deploy (Publikasikan)

  1. Klik Deploy > New deployment
  2. Klik ikon gear > pilih Web app
  3. Isi:
    • Description: Terserah, misal "My Database API"
    • Execute as: Me (Saya)
    • Who has access: Anyone (Siapa saja)
  4. Klik Deploy
  5. Salin URL Web App yang muncul (simpan, ini yang akan dipakai!)

Contoh URL:

https://script.google.com/macros/s/AKfycbx...xyz/exec

Gunakan di React

Langkah 1: Import

import { AppScriptProvider, useAppScriptQuery, useAppScriptMutation } from 'react-appscript-db';

Langkah 2: Setup Provider

Bungkus aplikasi kamu dengan Provider:

import React from 'react';
import { AppScriptProvider } from 'react-appscript-db';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import UserList from './UserList';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <AppScriptProvider config={{ scriptUrl: 'URL_APPSCRIPT_KAMU' }}>
        <h1>Website Saya</h1>
        <UserList />
      </AppScriptProvider>
    </QueryClientProvider>
  );
}

export default App;

Ganti URL_APPSCRIPT_KAMU dengan URL yang kamu salin tadi!

Langkah 3: Baca Data (Read)

import { useAppScriptQuery } from 'react-appscript-db';

function UserList() {
  // Mengambil data dari Google Sheets
  const { data: users, isLoading, error } = useAppScriptQuery(
    { scriptUrl: 'URL_APPSCRIPT_KAMU' },
    { 
      action: 'getData',
      params: { sheet: 'Sheet1' }  // Nama sheet kamu
    }
  );

  // Tampilkan loading
  if (isLoading) return <p>Loading...</p>;

  // Tampilkan error
  if (error) return <p>Error: {error.message}</p>;

  // Tampilkan data
  return (
    <ul>
      {users?.map((user, index) => (
        <li key={index}>
          {user[1]} - {user[2]}  {/* user[1] = nama, user[2] = email */}
        </li>
      ))}
    </ul>
  );
}

Langkah 4: Tambah Data (Create)

import { useAppScriptMutation } from 'react-appscript-db';

function AddUser() {
  const mutation = useAppScriptMutation(
    { scriptUrl: 'URL_APPSCRIPT_KAMU' },
    { 
      action: 'insertRow',
      invalidateQueries: [['appscript', 'URL_APPSCRIPT_KAMU', 'getData']]
    }
  );

  const handleSubmit = (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    
    mutation.mutate({
      values: [
        formData.get('nama'),
        formData.get('email'),
        formData.get('umur')
      ]
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="nama" placeholder="Nama" required />
      <input name="email" type="email" placeholder="Email" required />
      <input name="umur" type="number" placeholder="Umur" required />
      <button type="submit" disabled={mutation.isPending}>
        {mutation.isPending ? 'Menambahkan...' : 'Tambah'}
      </button>
    </form>
  );
}

Langkah 5: Edit Data (Update)

function EditUser({ userId, currentName }) {
  const mutation = useAppScriptMutation(
    { scriptUrl: 'URL_APPSCRIPT_KAMU' },
    { 
      action: 'updateRow',
      invalidateQueries: [['appscript', 'URL_APPSCRIPT_KAMU', 'getData']]
    }
  );

  const handleUpdate = () => {
    const newName = prompt('Nama baru:', currentName);
    if (newName) {
      mutation.mutate({
        row: userId,
        values: [newName]
      });
    }
  };

  return <button onClick={handleUpdate}>Edit</button>;
}

Langkah 6: Hapus Data (Delete)

function DeleteUser({ userId }) {
  const mutation = useAppScriptMutation(
    { scriptUrl: 'URL_APPSCRIPT_KAMU' },
    { 
      action: 'deleteRow',
      invalidateQueries: [['appscript', 'URL_APPSCRIPT_KAMU', 'getData']]
    }
  );

  return (
    <button onClick={() => {
      if (confirm('Yakin ingin hapus?')) {
        mutation.mutate({ row: userId });
      }
    }}>
      Hapus
    </button>
  );
}

Gunakan di Vanilla JS

Tanpa React, kamu bisa pakai langsung:

<!DOCTYPE html>
<html>
<head>
  <title>Database Sederhana</title>
</head>
<body>
  <h1>Daftar Pengguna</h1>
  <div id="loading">Loading...</div>
  <ul id="userList"></ul>

  <script type="module">
    import { appScriptFetch } from 'react-appscript-db/core';

    const SCRIPT_URL = 'URL_APPSCRIPT_KAMU';
    const config = { scriptUrl: SCRIPT_URL };

    async function loadUsers() {
      try {
        const users = await appScriptFetch(config, {
          action: 'getData',
          params: { sheet: 'Sheet1' }
        });

        document.getElementById('loading').style.display = 'none';
        
        const list = document.getElementById('userList');
        users.forEach(user => {
          const li = document.createElement('li');
          li.textContent = `${user[1]} - ${user[2]}`;
          list.appendChild(li);
        });
      } catch (error) {
        document.getElementById('loading').textContent = 'Error: ' + error.message;
      }
    }

    loadUsers();
  </script>
</body>
</html>

Contoh Lengkap

Lihat folder examples/ untuk contoh lengkap:

  • examples/react-basic/ - React dengan CRUD lengkap
  • examples/vanilla-js/ - Vanilla JS tanpa framework

Troubleshooting

Error: "Failed to fetch"

Penyebab: URL AppScript salah atau belum di-deploy.

Solusi:

  1. Pastikan URL benar (akhiran /exec)
  2. Pastikan sudah deploy di Apps Script
  3. Buka URL di browser, pastikan ada response JSON

Error: "CORS error"

Penyebab: Content-Type header salah.

Solusi: Package ini sudah menangani CORS secara otomatis. Jika masih error:

  1. Pastikan pakai versi terbaru
  2. Coba refresh browser (Ctrl+Shift+R)

Data tidak muncul

Penyebab: Nama sheet salah.

Solusi:

  1. Cek nama sheet di Google Sheets (lihat tab di bawah)
  2. Pastikan params: { sheet: 'NamaSheet' } sesuai

Error: "Unknown action"

Penyebab: Action name tidak sesuai.

Solusi: Pastikan action name sesuai:

  • getData - untuk membaca data
  • insertRow - untuk menambah data
  • updateRow - untuk mengedit data
  • deleteRow - untuk menghapus data

FAQ

Q: Apakah ini gratis?

A: Ya! Google Sheets dan Apps Script gratis. Package ini juga open source (MIT License).

Q: Berapa banyak data yang bisa disimpan?

A: Google Sheets bisa menyimpan hingga 10 juta sel. Untuk MVP atau portofolio, ini sangat cukup.

Q: Apakah aman?

A: Untuk data publik, ya. Jangan simpan data sensitif (password, data pribadi) di Google Sheets tanpa keamanan tambahan.

Q: Bisa dipakai untuk production?

A: Bisa untuk MVP atau project kecil. Untuk production berskala besar, pertimbangkan database dedicated seperti PostgreSQL atau MongoDB.

Q: Apakah harus pakai React?

A: Tidak! Package ini bisa dipakai dengan Vue, Svelte, Angular, atau vanilla JS. React hanya recommended.

Q: Kenapa data berupa array, bukan object?

A: Google Sheets mengembalikan data sebagai array of arrays. Kamu bisa mengubahnya:

const users = data.map(row => ({
  id: row[0],
  nama: row[1],
  email: row[2],
  umur: row[3]
}));

Glossary

| Istilah | Penjelasan | |---------|------------| | npm | Package manager untuk JavaScript | | Provider | Komponen React yang memberikan data ke semua komponen anak | | Hook | Fungsi React yang bisa dipakai di dalam komponen | | Query | Permintaan data dari server | | Mutation | Mengubah data (tambah/edit/hapus) | | CORS | Cross-Origin Resource Sharing, aturan keamanan browser | | Deploy | Membuat aplikasi bisa diakses publik | | API | Application Programming Interface, cara komunikasi antar aplikasi | | JSON | Format data yang umum digunakan di web | | TypeScript | JavaScript dengan tipe data |


Kontribusi

Ingin membantu? Silakan!

  1. Fork repository ini
  2. Buat branch baru (git checkout -b feature/fitur-baru)
  3. Commit perubahan (git commit -m 'Tambah fitur baru')
  4. Push ke branch (git push origin feature/fitur-baru)
  5. Buka Pull Request

License

MIT License - lihat file LICENSE untuk detail.


Acknowledgments

Terima kasih kepada:


English

If you prefer English, scroll up or click here.

react-appscript-db is a framework-agnostic npm package that provides React hooks (and vanilla JS support) to interact with Google Apps Script Web Apps backed by Google Sheets.

Key Features:

  • Works with React, Vue, Svelte, or vanilla JavaScript
  • React hooks with TanStack Query integration
  • Automatic caching and optimistic updates
  • CORS handling built-in
  • TypeScript support

Quick Install:

npm install react-appscript-db @tanstack/react-query

For full documentation, see the Indonesian version above.