Course contentsShow
← React
Lesson 1825 of 2,39642. Data Fetching LibrariesFree lesson

useMutation for Writing Data

Executing mutations with useMutation, handling mutation state, and accessing mutation results and errors.

useMutation for Writing Data

What you'll learn: How to execute GraphQL mutations with Apollo Client's useMutation hook to modify server data and handle the operation's lifecycle.

The Core Idea

While useQuery fetches data, useMutation performs write operations—creating, updating, or deleting data on your GraphQL server. Unlike queries that run automatically, mutations execute only when you explicitly trigger them. The hook returns a function to execute the mutation plus an object tracking its progress (loading, error, and result states).

How It Works

Import useMutation and your GraphQL mutation document:

import { gql, useMutation } from '@apollo/client';

const ADD_TODO = gql`
  mutation AddTodo($text: String!) {
    addTodo(text: $text) {
      id
      text
      completed
    }
  }
`;

function TodoForm() {
  const [addTodo, { data, loading, error }] = useMutation(ADD_TODO);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const text = e.target.todoText.value;
    
    await addTodo({ variables: { text } });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="todoText" disabled={loading} />
      <button type="submit">
        {loading ? 'Adding...' : 'Add Todo'}
      </button>
      {error && <p>Error: {error.message}</p>}
      {data && <p>Added: {data.addTodo.text}</p>}
    </form>
  );
}

The hook returns an array: the mutation function and a result object. Call the function with variables to execute. The result object tracks loading, error, and data throughout the operation's lifecycle.

The Mental Model

Think of useMutation like submitting a form—you fill it out (prepare variables), click submit (call the mutation function), and wait for confirmation (monitor loading/error/data states).

Key Takeaway: useMutation provides a mutation function to trigger write operations on demand, plus state tracking for loading, errors, and results throughout the mutation lifecycle.