Advanced mutation patterns with TanStack Query for Google Antigravity IDE
# 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.This React 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 react 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 React projects, consider mentioning your framework version, coding style, and any specific libraries you're using.