Sub topic 8
Changing server data with useMutation
This chapter assumes you can write useQuery calls, understand query keys, and know how to send POST, PATCH, and DELETE requests with fetch. Queries read data. Mutations create, update, or delete it.
How a mutation differs from a query
A query runs automatically when a component mounts, and its result is cached under a key. A mutation does none of that. It runs only when you call it, so it fits side effects such as submitting a form or deleting a row.
| Row | `useQuery` | `useMutation` |
|---|---|---|
| Starts | Automatically | When you call `mutate` |
| Cached by key | Yes | No |
| Retries on failure | 3 times by default | 0 times by default |
| Purpose | Read data | Change data |
A basic mutation
useMutation takes a mutationFn that receives the variables you pass to mutate. As with queries, the function must throw on failure. fetch does not reject on HTTP error codes, so check res.ok.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
async function createTodo(title: string): Promise<Todo> {
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
})
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export function AddTodoForm() {
const [title, setTitle] = useState('')
const addTodo = useMutation({
mutationFn: createTodo,
onSuccess: () => setTitle(''),
})
return (
<form
onSubmit={(e) => {
e.preventDefault()
addTodo.mutate(title)
}}
>
<input value={title} onChange={(e) => setTitle(e.target.value)} />
<button type="submit" disabled={addTodo.isPending}>
{addTodo.isPending ? 'Saving...' : 'Add todo'}
</button>
{addTodo.isError && <p>Could not save: {addTodo.error.message}</p>}
</form>
)
}The component must still be wrapped in a QueryClientProvider, as in the setup chapter.
Mutation status
A mutation moves through four states. They are idle before the first call, pending while the request runs, then success or error. The hook exposes them as isIdle, isPending, isSuccess, and isError.
Callbacks
You can attach lifecycle callbacks in two places.
useMutation({ onSuccess, onError, onSettled })runs for every call. Use it for work tied to the mutation itself, such as refreshing the cache.mutate(variables, { onSuccess, onError, onSettled })runs for that call only. Use it for UI work such as closing a dialog.
onSettled runs after either outcome. Per-call callbacks do not fire if the component unmounts before the request finishes. Hook-level callbacks still fire.
mutate or mutateAsync
mutate returns nothing and handles errors through the state and callbacks. mutateAsync returns a Promise, so you can await it, but you must catch its rejection yourself.
try {
const todo = await addTodo.mutateAsync('Write tutorial')
console.log('Created', todo.id)
} catch (error) {
console.error('Save failed', error)
}Prefer mutate unless you need to chain work after the result.
What a mutation does not do
A successful mutation does not update any query. If ['todos'] is on screen, it still shows the old list. The next chapter covers invalidation, which marks affected queries stale and refetches them.
Exercise
A user submits a form, and the server responds with status 500. The mutationFn calls fetch and returns res.json() without checking res.ok. What is isError afterwards, and how do you fix it?
Show answer
isError stays false and the mutation ends in success. fetch resolves on a 500 response, so TanStack Query sees no failure. Fix it by adding if (!res.ok) throw new Error(...) before returning res.json().