Build offline-first applications with IndexedDB storage patterns for Google Antigravity projects.
# IndexedDB Offline Storage for Google Antigravity
IndexedDB provides a powerful client-side database for building offline-first applications. This guide covers modern patterns for using IndexedDB in Google Antigravity projects.
## Database Wrapper Class
```typescript
// lib/indexed-db.ts
export class IndexedDBStore<T extends { id: string }> {
private db: IDBDatabase | null = null;
private dbName: string;
private storeName: string;
private version: number;
constructor(dbName: string, storeName: string, version = 1) {
this.dbName = dbName;
this.storeName = storeName;
this.version = version;
}
async init(): Promise<void> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.dbName, this.version);
request.onerror = () => reject(request.error);
request.onsuccess = () => { this.db = request.result; resolve(); };
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
if (!db.objectStoreNames.contains(this.storeName)) {
const store = db.createObjectStore(this.storeName, { keyPath: "id" });
store.createIndex("updatedAt", "updatedAt", { unique: false });
store.createIndex("syncStatus", "syncStatus", { unique: false });
}
};
});
}
async put(item: T): Promise<void> {
return new Promise((resolve, reject) => {
const transaction = this.db!.transaction(this.storeName, "readwrite");
const store = transaction.objectStore(this.storeName);
const request = store.put({ ...item, updatedAt: Date.now(), syncStatus: "pending" });
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
});
}
async get(id: string): Promise<T | undefined> {
return new Promise((resolve, reject) => {
const transaction = this.db!.transaction(this.storeName, "readonly");
const request = transaction.objectStore(this.storeName).get(id);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
}
async getAll(): Promise<T[]> {
return new Promise((resolve, reject) => {
const transaction = this.db!.transaction(this.storeName, "readonly");
const request = transaction.objectStore(this.storeName).getAll();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
}
async delete(id: string): Promise<void> {
return new Promise((resolve, reject) => {
const transaction = this.db!.transaction(this.storeName, "readwrite");
const request = transaction.objectStore(this.storeName).delete(id);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
});
}
async getPendingSync(): Promise<T[]> {
return new Promise((resolve, reject) => {
const transaction = this.db!.transaction(this.storeName, "readonly");
const index = transaction.objectStore(this.storeName).index("syncStatus");
const request = index.getAll("pending");
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
}
}
```
## React Hook for IndexedDB
```typescript
// hooks/useIndexedDB.ts
import { useState, useEffect, useCallback } from "react";
import { IndexedDBStore } from "@/lib/indexed-db";
export function useIndexedDB<T extends { id: string }>(dbName: string, storeName: string) {
const [store, setStore] = useState<IndexedDBStore<T> | null>(null);
const [data, setData] = useState<T[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
const initStore = async () => {
try {
const dbStore = new IndexedDBStore<T>(dbName, storeName);
await dbStore.init();
setStore(dbStore);
const items = await dbStore.getAll();
setData(items);
} catch (err) {
setError(err instanceof Error ? err : new Error("Init failed"));
} finally {
setLoading(false);
}
};
initStore();
}, [dbName, storeName]);
const addItem = useCallback(async (item: T) => {
if (!store) return;
await store.put(item);
setData((prev) => [...prev.filter((i) => i.id !== item.id), item]);
}, [store]);
const removeItem = useCallback(async (id: string) => {
if (!store) return;
await store.delete(id);
setData((prev) => prev.filter((i) => i.id !== id));
}, [store]);
return { data, loading, error, addItem, removeItem };
}
```
## Sync Manager
```typescript
// lib/sync-manager.ts
export class SyncManager<T extends { id: string }> {
private store: IndexedDBStore<T>;
private syncEndpoint: string;
private syncInProgress = false;
constructor(store: IndexedDBStore<T>, syncEndpoint: string) {
this.store = store;
this.syncEndpoint = syncEndpoint;
window.addEventListener("online", () => this.sync());
}
async sync(): Promise<void> {
if (this.syncInProgress || !navigator.onLine) return;
this.syncInProgress = true;
try {
const pendingItems = await this.store.getPendingSync();
for (const item of pendingItems) {
const response = await fetch(this.syncEndpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(item),
});
if (response.ok) await this.store.put({ ...item, syncStatus: "synced" } as T);
}
} finally {
this.syncInProgress = false;
}
}
}
```
## Best Practices
1. **Versioning**: Implement proper database versioning for schema migrations
2. **Error Recovery**: Handle quota exceeded errors and provide user feedback
3. **Background Sync**: Use Service Workers for background synchronization
4. **Transactions**: Use transactions for atomic operations on multiple records
5. **Cleanup**: Implement data expiration policies to manage storage limitsThis indexeddb prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their indexeddb implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For indexeddb projects, consider mentioning your framework version, coding style, and any specific libraries you're using.