Build real-time reactive applications with Convex backend in Google Antigravity with automatic sync and optimistic updates
# Convex Reactive Database Patterns for Google Antigravity
Real-time data synchronization creates engaging user experiences but is traditionally complex to implement. This guide establishes patterns for integrating Convex with Google Antigravity projects, enabling Gemini 3 to generate reactive backends with automatic data sync.
## Schema Definition
Define type-safe schemas with Convex:
```typescript
// convex/schema.ts
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
users: defineTable({
clerkId: v.string(),
email: v.string(),
name: v.string(),
avatarUrl: v.optional(v.string()),
createdAt: v.number(),
})
.index("by_clerk_id", ["clerkId"])
.index("by_email", ["email"]),
messages: defineTable({
channelId: v.id("channels"),
authorId: v.id("users"),
content: v.string(),
attachments: v.optional(v.array(v.string())),
createdAt: v.number(),
updatedAt: v.optional(v.number()),
})
.index("by_channel", ["channelId", "createdAt"])
.index("by_author", ["authorId"]),
channels: defineTable({
name: v.string(),
description: v.optional(v.string()),
isPrivate: v.boolean(),
members: v.array(v.id("users")),
createdBy: v.id("users"),
createdAt: v.number(),
})
.index("by_name", ["name"])
.searchIndex("search_name", { searchField: "name" }),
presence: defineTable({
userId: v.id("users"),
channelId: v.id("channels"),
lastSeen: v.number(),
isTyping: v.boolean(),
})
.index("by_channel", ["channelId"])
.index("by_user", ["userId"]),
});
```
## Query Functions
Create reactive queries that automatically update:
```typescript
// convex/messages.ts
import { query, mutation } from "./_generated/server";
import { v } from "convex/values";
import { paginationOptsValidator } from "convex/server";
export const listByChannel = query({
args: {
channelId: v.id("channels"),
paginationOpts: paginationOptsValidator,
},
handler: async (ctx, args) => {
const messages = await ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
.order("desc")
.paginate(args.paginationOpts);
// Enrich messages with author data
const enrichedMessages = await Promise.all(
messages.page.map(async (message) => {
const author = await ctx.db.get(message.authorId);
return { ...message, author };
})
);
return { ...messages, page: enrichedMessages };
},
});
export const send = mutation({
args: {
channelId: v.id("channels"),
content: v.string(),
attachments: v.optional(v.array(v.string())),
},
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Unauthenticated");
const user = await ctx.db
.query("users")
.withIndex("by_clerk_id", (q) => q.eq("clerkId", identity.subject))
.unique();
if (!user) throw new Error("User not found");
const messageId = await ctx.db.insert("messages", {
channelId: args.channelId,
authorId: user._id,
content: args.content,
attachments: args.attachments,
createdAt: Date.now(),
});
// Update typing indicator
await ctx.db
.query("presence")
.withIndex("by_user", (q) => q.eq("userId", user._id))
.unique()
.then(async (presence) => {
if (presence) {
await ctx.db.patch(presence._id, { isTyping: false });
}
});
return messageId;
},
});
```
## React Integration
Use Convex hooks for reactive UI:
```typescript
// components/ChatMessages.tsx
"use client";
import { useQuery, useMutation, usePaginatedQuery } from "convex/react";
import { api } from "@/convex/_generated/api";
import { Id } from "@/convex/_generated/dataModel";
import { useCallback, useRef, useEffect } from "react";
interface ChatMessagesProps {
channelId: Id<"channels">;
}
export function ChatMessages({ channelId }: ChatMessagesProps) {
const { results, status, loadMore } = usePaginatedQuery(
api.messages.listByChannel,
{ channelId },
{ initialNumItems: 50 }
);
const sendMessage = useMutation(api.messages.send);
const messagesEndRef = useRef<HTMLDivElement>(null);
const scrollToBottom = useCallback(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, []);
useEffect(() => {
scrollToBottom();
}, [results, scrollToBottom]);
const handleSend = async (content: string) => {
await sendMessage({ channelId, content });
};
return (
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto p-4 space-y-4">
{status === "CanLoadMore" && (
<button onClick={() => loadMore(50)} className="text-blue-500">
Load earlier messages
</button>
)}
{results?.map((message) => (
<MessageBubble key={message._id} message={message} />
))}
<div ref={messagesEndRef} />
</div>
<MessageInput onSend={handleSend} />
</div>
);
}
```
## Best Practices
1. **Schema design**: Use indexes for efficient queries
2. **Pagination**: Implement pagination for large datasets
3. **Optimistic updates**: Leverage Convex's built-in optimistic updates
4. **Authentication**: Integrate with Clerk or Auth0 for identity
5. **Error handling**: Handle network errors gracefullyThis Convex 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 convex 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 Convex projects, consider mentioning your framework version, coding style, and any specific libraries you're using.