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
TanStack Query Mutation Patterns

TanStack Query Mutation Patterns

Advanced mutation patterns with TanStack Query for Google Antigravity IDE

ReactTanStack QueryData FetchingState Management
by Antigravity AI
⭐0Stars
.antigravity
# TanStack Query Mutation Patterns for Google Antigravity

Master data mutations in React applications using TanStack Query with Google Antigravity IDE. This comprehensive guide covers optimistic updates, mutation lifecycles, error handling, cache invalidation strategies, and advanced patterns for building robust data mutation workflows.

## Configuration

Configure your Antigravity environment for mutation handling:

```typescript
// .antigravity/tanstack-query.ts
export const queryConfig = {
  mutations: {
    optimisticUpdates: true,
    retryOnFailure: 3,
    rollbackOnError: true,
    invalidateOnSuccess: true
  },
  errorHandling: {
    globalErrorBoundary: true,
    toastNotifications: true
  }
};
```

## Basic Mutation Pattern

Create type-safe mutations with proper error handling:

```typescript
import { useMutation, useQueryClient } from "@tanstack/react-query";

interface CreatePostInput {
  title: string;
  content: string;
  authorId: string;
}

interface Post {
  id: string;
  title: string;
  content: string;
  authorId: string;
  createdAt: Date;
}

async function createPost(input: CreatePostInput): Promise<Post> {
  const response = await fetch("/api/posts", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(input)
  });
  
  if (!response.ok) {
    throw new Error("Failed to create post");
  }
  
  return response.json();
}

export function useCreatePost() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: createPost,
    onSuccess: (newPost) => {
      queryClient.invalidateQueries({ queryKey: ["posts"] });
      queryClient.setQueryData(["posts", newPost.id], newPost);
    },
    onError: (error) => {
      console.error("Failed to create post:", error);
    }
  });
}
```

## Optimistic Updates Pattern

Implement instant UI feedback with rollback:

```typescript
export function useUpdatePost() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ id, ...data }: UpdatePostInput) => {
      const response = await fetch(`/api/posts/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
      });
      return response.json();
    },
    onMutate: async (updatedPost) => {
      await queryClient.cancelQueries({ queryKey: ["posts", updatedPost.id] });

      const previousPost = queryClient.getQueryData<Post>(["posts", updatedPost.id]);

      queryClient.setQueryData(["posts", updatedPost.id], (old: Post) => ({
        ...old,
        ...updatedPost
      }));

      return { previousPost };
    },
    onError: (err, updatedPost, context) => {
      if (context?.previousPost) {
        queryClient.setQueryData(
          ["posts", updatedPost.id],
          context.previousPost
        );
      }
    },
    onSettled: (data, error, variables) => {
      queryClient.invalidateQueries({ queryKey: ["posts", variables.id] });
    }
  });
}
```

## Mutation with Dependent Queries

Handle mutations that affect multiple queries:

```typescript
export function useDeletePost() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (postId: string) => {
      await fetch(`/api/posts/${postId}`, { method: "DELETE" });
      return postId;
    },
    onMutate: async (postId) => {
      await queryClient.cancelQueries({ queryKey: ["posts"] });

      const previousPosts = queryClient.getQueryData<Post[]>(["posts"]);

      queryClient.setQueryData<Post[]>(["posts"], (old) =>
        old?.filter((post) => post.id !== postId)
      );

      queryClient.removeQueries({ queryKey: ["posts", postId] });

      return { previousPosts };
    },
    onError: (err, postId, context) => {
      queryClient.setQueryData(["posts"], context?.previousPosts);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["posts"] });
      queryClient.invalidateQueries({ queryKey: ["user", "stats"] });
    }
  });
}
```

## Mutation Queue Pattern

Process mutations sequentially:

```typescript
const mutationQueue = new Map<string, Promise<unknown>>();

export function useQueuedMutation<TData, TVariables>(
  mutationFn: (variables: TVariables) => Promise<TData>,
  queueKey: string
) {
  return useMutation({
    mutationFn: async (variables: TVariables) => {
      const previousPromise = mutationQueue.get(queueKey) || Promise.resolve();
      
      const newPromise = previousPromise.then(() => mutationFn(variables));
      mutationQueue.set(queueKey, newPromise);
      
      return newPromise;
    }
  });
}
```

## Form Integration Pattern

Integrate mutations with form libraries:

```typescript
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";

export function CreatePostForm() {
  const createPost = useCreatePost();
  
  const form = useForm<CreatePostInput>({
    resolver: zodResolver(createPostSchema),
    defaultValues: { title: "", content: "" }
  });

  const onSubmit = form.handleSubmit((data) => {
    createPost.mutate(data, {
      onSuccess: () => {
        form.reset();
      }
    });
  });

  return (
    <form onSubmit={onSubmit}>
      <input {...form.register("title")} disabled={createPost.isPending} />
      <textarea {...form.register("content")} disabled={createPost.isPending} />
      <button type="submit" disabled={createPost.isPending}>
        {createPost.isPending ? "Creating..." : "Create Post"}
      </button>
    </form>
  );
}
```

## Best Practices

Follow these guidelines for robust mutations:

1. **Always handle errors** - Provide user feedback on failures
2. **Use optimistic updates** - Improve perceived performance
3. **Implement rollback** - Restore state on mutation failure
4. **Invalidate strategically** - Only invalidate affected queries
5. **Cancel in-flight queries** - Prevent race conditions
6. **Type your mutations** - Ensure type safety throughout

Google Antigravity IDE provides intelligent mutation scaffolding and cache invalidation suggestions for optimal data management.

When to Use This Prompt

This React prompt is ideal for developers working on:

  • React applications requiring modern best practices and optimal performance
  • Projects that need production-ready React code with proper error handling
  • Teams looking to standardize their react development workflow
  • Developers wanting to learn industry-standard React 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 react 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 React 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 React 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 React projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...