# Mutations Reference ## Table of Contents - [useMutation Hook](#usemutation-hook) - [Mutation Variables](#mutation-variables) - [Loading and Error States](#loading-and-error-states) - [Optimistic UI](#optimistic-ui) - [Cache Updates](#cache-updates) - [Refetch Queries](#refetch-queries) - [Error Handling](#error-handling) ## useMutation Hook The `useMutation` hook is used to execute GraphQL mutations. ### Basic Usage ```tsx import { gql } from "@apollo/client"; import { useMutation } from "@apollo/client/react"; const ADD_TODO = gql` mutation AddTodo($text: String!) { addTodo(text: $text) { id text completed } } `; function AddTodo() { const [addTodo, { data, loading, error }] = useMutation(ADD_TODO); return (
{ e.preventDefault(); const form = e.currentTarget; const text = new FormData(form).get("text") as string; addTodo({ variables: { text } }); form.reset(); }} > {error &&

Error: {error.message}

}
); } ``` ### Return Tuple ```typescript const [ mutateFunction, // Function to call to execute mutation { data, // Mutation result data loading, // True while mutation is in flight error, // ApolloError if mutation failed called, // True if mutation has been called reset, // Reset mutation state client, // Apollo Client instance }, ] = useMutation(MUTATION); ``` ## Mutation Variables ### Variables in Options ```tsx const [createUser] = useMutation(CREATE_USER, { variables: { input: { name: "Default User", email: "default@example.com", }, }, }); // Call with default variables await createUser(); // Override variables await createUser({ variables: { input: { name: "Custom User", email: "custom@example.com", }, }, }); ``` ### TypeScript Types Use `TypedDocumentNode` instead of generic type parameters: ```typescript import { gql, TypedDocumentNode } from "@apollo/client"; interface CreateUserData { createUser: { id: string; name: string; email: string; }; } interface CreateUserVariables { input: { name: string; email: string; }; } const CREATE_USER: TypedDocumentNode = gql` mutation CreateUser($input: CreateUserInput!) { createUser(input: $input) { id name email } } `; const [createUser, { data, loading }] = useMutation(CREATE_USER); const { data } = await createUser({ variables: { input: { name: "John", email: "john@example.com" }, }, }); // data.createUser is fully typed ``` ## Loading and Error States ### Handling in UI ```tsx function CreatePost() { const [createPost, { loading, error, data, reset }] = useMutation(CREATE_POST); if (data) { return (

Post created: {data.createPost.title}

); } return (