Sub topic 13
Updating server data with mutations
This chapter assumes you can read data with useQuery, know what a query key is, and understand that TanStack Query keeps a cache of server data. Here you will send changes to the server and make the screen match the result.
Queries read, mutations write
A query describes data you want to read. It can run again at any time without side effects. A mutation is a request that changes something on the server, such as a POST, PUT, PATCH, or DELETE. It must run only when the user asks for it, so TanStack Query never runs it automatically.
useMutation returns an object with a mutate function and the state of the last call. You call mutate from an event handler, not during render.
A first mutation
import { useMutation, useQueryClient } from '@tanstack/react-query';
function RenameUser({ userId }) {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: async (name) => {
const response = await fetch(`/api/users/${userId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name }),
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['user', userId] });
},
});
return (
<button onClick={() => mutation.mutate('Ada')} disabled={mutation.isPending}>
Rename
</button>
);
}mutationFn receives the value passed to mutate. As with queries, fetch does not reject on a 404 or 500, so the function checks response.ok and throws. Without that check, a failed request would count as a success.
The isPending flag is true while the request is in flight. Disabling the button with it prevents double submits.
Invalidating cached data
After the server changes, the cached copy of that data is out of date. invalidateQueries marks matching queries as stale. If a component is currently using one of them, TanStack Query refetches it right away. Components that are not on screen refetch the next time they mount.
Matching works by key prefix. Invalidating ['user', userId] also matches ['user', userId, 'posts']. Invalidating ['user'] matches every user query. Choose the narrowest key that covers the data you changed.
Showing mutation state
The mutation object exposes the same kind of state a query does.
| Property | Meaning |
|---|---|
| `isPending` | The request is in flight. |
| `isError` and `error` | The last call failed, and why. |
| `isSuccess` | The last call succeeded. |
| `data` | The value returned by `mutationFn`. |
You can also pass callbacks to mutate itself, for example mutation.mutate('Ada', { onSuccess: closeDialog }). These run only for the latest call and only if the component is still mounted. Put cache logic in useMutation, and put UI reactions such as closing a dialog in mutate.
Common errors
- Forgetting to invalidate. The request succeeds but the screen shows old data until something else triggers a refetch.
- Skipping the
response.okcheck. The mutation reports success after a server error, soonSuccessinvalidates data that never changed. - Calling
mutateduring render. This sends a request on every render. Call it only from handlers or effects tied to a user action. - Using an overly broad key. Invalidating
[]refetches everything and wastes requests.
Exercise
A user clicks Rename and the request returns status 500. The button re-enables, but the page shows the old name and no error message. Name two things missing from the mutation code that would make this behavior correct and visible.
Show answer
First, mutationFn must check response.ok and throw on a 500, otherwise TanStack Query treats the call as a success. Second, the component should render mutation.isError and mutation.error.message so the user sees the failure. The old name is correct in this case, because the server did not change, and invalidation in onSuccess should not run.