Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
ElectricSQL Local-First Patterns

ElectricSQL Local-First Patterns

Master ElectricSQL local-first patterns for Google Antigravity IDE offline-capable applications

ElectricSQLLocal-FirstOfflineTypeScript
by Antigravity AI
⭐0Stars
.antigravity
# 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.

When to Use This Prompt

This ElectricSQL prompt is ideal for developers working on:

  • ElectricSQL applications requiring modern best practices and optimal performance
  • Projects that need production-ready ElectricSQL code with proper error handling
  • Teams looking to standardize their electricsql development workflow
  • Developers wanting to learn industry-standard ElectricSQL patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the ElectricSQL code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this ElectricSQL prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...