Master ElectricSQL local-first patterns for Google Antigravity IDE offline-capable applications
# ElectricSQL Local-First Patterns for Google Antigravity IDE
Build offline-first applications with ElectricSQL using Google Antigravity IDE. This guide covers local database sync, conflict resolution, optimistic updates, and real-time collaboration patterns.
## Core Setup
```typescript
// src/lib/electric.ts
import { ElectricDatabase, electrify } from "electric-sql/browser";
import { schema } from "./schema";
import { ElectricClient } from "electric-sql/client/model";
export type Electric = ElectricClient<typeof schema>;
let electric: Electric | null = null;
export async function initElectric(authToken: string): Promise<Electric> {
if (electric) return electric;
const conn = await ElectricDatabase.init("my-app.db");
electric = await electrify(conn, schema, {
url: process.env.NEXT_PUBLIC_ELECTRIC_URL!,
auth: {
token: authToken,
},
debug: process.env.NODE_ENV === "development",
});
// Connect to sync service
await electric.connect(authToken);
return electric;
}
export function getElectric(): Electric {
if (!electric) {
throw new Error("Electric not initialized. Call initElectric first.");
}
return electric;
}
```
## Schema Definition
```typescript
// src/lib/schema.ts
import { z } from "zod";
import { createTableSchema, createDbSchema, HKT } from "electric-sql/client/model";
// Define shapes for type safety
const todoShape = {
id: z.string().uuid(),
title: z.string(),
completed: z.boolean(),
list_id: z.string().uuid(),
created_at: z.coerce.date(),
updated_at: z.coerce.date(),
synced: z.boolean().default(false),
};
const listShape = {
id: z.string().uuid(),
name: z.string(),
owner_id: z.string().uuid(),
created_at: z.coerce.date(),
shared_with: z.array(z.string().uuid()).default([]),
};
// Create table schemas
const todos = createTableSchema("todos", todoShape);
const lists = createTableSchema("lists", listShape);
// Export the complete schema
export const schema = createDbSchema({
todos,
lists,
});
export type Todo = z.infer<typeof todos.schema>;
export type List = z.infer<typeof lists.schema>;
```
## React Hooks Integration
```typescript
// src/hooks/useElectric.ts
import { useLiveQuery } from "electric-sql/react";
import { getElectric, type Electric } from "@/lib/electric";
import { useCallback, useMemo } from "react";
import type { Todo, List } from "@/lib/schema";
export function useTodos(listId: string) {
const electric = getElectric();
const { results: todos, error } = useLiveQuery(
electric.db.todos.liveMany({
where: { list_id: listId },
orderBy: { created_at: "desc" },
})
);
const addTodo = useCallback(
async (title: string) => {
await electric.db.todos.create({
data: {
id: crypto.randomUUID(),
title,
completed: false,
list_id: listId,
created_at: new Date(),
updated_at: new Date(),
synced: false,
},
});
},
[electric, listId]
);
const toggleTodo = useCallback(
async (id: string, completed: boolean) => {
await electric.db.todos.update({
where: { id },
data: {
completed,
updated_at: new Date(),
synced: false,
},
});
},
[electric]
);
const deleteTodo = useCallback(
async (id: string) => {
await electric.db.todos.delete({
where: { id },
});
},
[electric]
);
return {
todos: todos ?? [],
error,
addTodo,
toggleTodo,
deleteTodo,
};
}
export function useLists(userId: string) {
const electric = getElectric();
const { results: lists } = useLiveQuery(
electric.db.lists.liveMany({
where: {
OR: [
{ owner_id: userId },
{ shared_with: { has: userId } },
],
},
orderBy: { created_at: "desc" },
})
);
const createList = useCallback(
async (name: string) => {
await electric.db.lists.create({
data: {
id: crypto.randomUUID(),
name,
owner_id: userId,
created_at: new Date(),
shared_with: [],
},
});
},
[electric, userId]
);
const shareList = useCallback(
async (listId: string, userIds: string[]) => {
const list = await electric.db.lists.findUnique({
where: { id: listId },
});
if (list) {
await electric.db.lists.update({
where: { id: listId },
data: {
shared_with: [...new Set([...list.shared_with, ...userIds])],
},
});
}
},
[electric]
);
return {
lists: lists ?? [],
createList,
shareList,
};
}
```
## Sync Status Component
```typescript
// src/components/SyncStatus.tsx
"use client";
import { useSyncStatus, useConnectivityState } from "electric-sql/react";
import { getElectric } from "@/lib/electric";
export function SyncStatus() {
const electric = getElectric();
const { state } = useConnectivityState(electric);
const { synced, pending } = useSyncStatus(electric);
return (
<div className="sync-status">
<div className={`status-indicator ${state}`}>
{state === "connected" && synced && (
<span className="synced">✓ Synced</span>
)}
{state === "connected" && !synced && (
<span className="syncing">↻ Syncing ({pending} pending)</span>
)}
{state === "disconnected" && (
<span className="offline">○ Offline</span>
)}
</div>
{state === "disconnected" && (
<button onClick={() => electric.connect()}>
Reconnect
</button>
)}
</div>
);
}
```
## Conflict Resolution
```typescript
// src/lib/conflict-resolution.ts
import { getElectric } from "./electric";
// Custom conflict resolver for todos
export function setupConflictResolution() {
const electric = getElectric();
electric.onConflict("todos", async (local, remote, base) => {
// Last-write-wins for simple fields
if (local.updated_at > remote.updated_at) {
return local;
}
// Merge completed status (prefer completed)
if (local.completed !== remote.completed) {
return {
...remote,
completed: local.completed || remote.completed,
};
}
return remote;
});
}
```
## Best Practices for Google Antigravity IDE
When using ElectricSQL with Google Antigravity, design schemas for local-first operation. Implement optimistic updates for instant UI. Handle connectivity state changes gracefully. Set up conflict resolution strategies. Use live queries for reactive UI. Let Gemini 3 generate sync-aware data models.
Google Antigravity excels at building offline-capable applications with ElectricSQL.This ElectricSQL 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 electricsql 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 ElectricSQL projects, consider mentioning your framework version, coding style, and any specific libraries you're using.