0
0
GraphqlHow-ToBeginner · 3 min read

How to Use useMutation Hook in Apollo Client

Use the useMutation hook from Apollo Client to run GraphQL mutations in React. It returns a mutation function and an object with mutation status, which you call with variables to update data on the server.
📐

Syntax

The useMutation hook takes a GraphQL mutation query as input and returns an array with two elements: a mutation function and an object containing the mutation state.

  • Mutation query: The GraphQL mutation you want to execute.
  • Mutation function: Call this function to run the mutation, optionally passing variables.
  • Mutation result object: Contains data, loading, and error states.
javascript
const [mutateFunction, { data, loading, error }] = useMutation(MY_MUTATION);
💻

Example

This example shows how to use useMutation to add a new item by calling the mutation function with variables. It handles loading and error states and displays the result.

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

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

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

  const handleAdd = () => {
    addTodo({ variables: { text: 'Learn Apollo useMutation' } });
  };

  if (loading) return <p>Adding todo...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <button onClick={handleAdd}>Add Todo</button>
      {data && <p>Added: {data.addTodo.text}</p>}
    </div>
  );
}

export default AddTodo;
Output
<button>Add Todo</button> <p>Adding todo...</p> (while loading) <p>Added: Learn Apollo useMutation</p> (after success)
⚠️

Common Pitfalls

  • Not passing variables correctly to the mutation function causes errors.
  • Ignoring loading and error states can lead to poor user experience.
  • Calling the mutation function without parentheses or forgetting to await async results.
  • Mutations must be defined with gql and include required variables.
javascript
/* Wrong: Missing variables */
addTodo();

/* Right: Pass variables as an object */
addTodo({ variables: { text: 'New task' } });
📊

Quick Reference

StepDescription
Import useMutationimport { useMutation } from '@apollo/client';
Define mutationUse gql to write your mutation query.
Call useMutationconst [mutate, { data, loading, error }] = useMutation(MY_MUTATION);
Execute mutationCall mutate({ variables: { ... } }) to run it.
Handle statesUse loading and error to update UI accordingly.

Key Takeaways

useMutation returns a function to trigger the mutation and an object with status info.
Always pass variables as an object to the mutation function when needed.
Handle loading and error states to improve user experience.
Define mutations with gql and import useMutation from @apollo/client.
Call the mutation function with parentheses and variables to execute the mutation.