0
0
GraphQLquery~5 mins

useMutation hook in GraphQL

Choose your learning style9 modes available
Introduction

The useMutation hook helps you change data on the server, like adding or updating information.

When you want to add a new item to a list, like a new user or post.
When you need to update existing information, such as changing a user's email.
When you want to delete an item from the database.
When you want to send a form and save the data on the server.
Syntax
GraphQL
const [mutateFunction, { data, loading, error }] = useMutation(MUTATION_QUERY);

mutateFunction is called to run the mutation.

The object contains data (result), loading (in progress), and error (if any).

Examples
This sets up a function addUser to add a user when called.
GraphQL
const [addUser] = useMutation(ADD_USER);
This sets up updatePost and tracks the mutation status.
GraphQL
const [updatePost, { data, loading, error }] = useMutation(UPDATE_POST);
Sample Program

This example shows how to add a new todo item using useMutation. When the button is clicked, it sends the new todo text to the server.

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

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

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

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

  if (loading) return 'Saving...';
  if (error) return `Error! ${error.message}`;

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

Always handle loading and error states to improve user experience.

Pass variables as an object inside the mutateFunction call.

Summary

useMutation lets you send changes to the server.

Call the mutation function with needed data to update the database.

Watch for loading and error to know what is happening.