Introduction
The useMutation hook helps you change data on the server, like adding or updating information.
Jump into concepts and practice - no test required
The useMutation hook helps you change data on the server, like adding or updating information.
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).
addUser to add a user when called.const [addUser] = useMutation(ADD_USER);updatePost and tracks the mutation status.const [updatePost, { data, loading, error }] = useMutation(UPDATE_POST);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.
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>} </> ); }
Always handle loading and error states to improve user experience.
Pass variables as an object inside the mutateFunction call.
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.
useMutation hook in GraphQL?useMutation hook is designed to send changes or updates to the server, such as creating, updating, or deleting data.useQuery which fetches data, useMutation is for sending data changes.useMutation?useMutation returns an array where the first element is the mutation function.variables key holding the data to send.loading immediately after calling addPost({ variables: { title: 'Hello' } })?
const [addPost, { loading, error }] = useMutation(ADD_POST);
addPost({ variables: { title: 'Hello' } });loading becomes true until the server responds.addPost, the mutation is in progress, so loading is true.useMutation:
const [updateUser, { loading, error }] = useMutation(UPDATE_USER);
updateUser({ name: 'Bob' });variables key, but here it is called with { name: 'Bob' } directly.updateUser({ variables: { name: 'Bob' } }).useMutation is best to ensure the UI shows fresh data?refetchQueries option with useMutation triggers a fresh fetch of specified queries, ensuring updated UI.