Invalidate queries after a mutation with TanStack Query
Refetch a cached list after a write by calling invalidateQueries in the onSuccess of useMutation, so the screen matches the server.
You add a todo and the list still shows the old data. After a mutation, mark the related queries stale so they refetch.
import { useMutation, useQueryClient } from '@tanstack/react-query';
export function AddTodo() {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: (title) =>
fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
}).then((res) => {
if (!res.ok) throw new Error('Save failed');
return res.json();
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] });
},
});
return (
<button disabled={mutation.isPending} onClick={() => mutation.mutate('Write snippet')}>
{mutation.isPending ? 'Saving…' : 'Add todo'}
</button>
);
}POST /api/todos -> 201
GET /api/todos -> 200 (refetched, the list shows the new todo)invalidateQueries({ queryKey: ['todos'] }) marks every query whose key starts with ['todos'] as stale. Those currently on screen refetch right away, and the rest refetch the next time they are used. onSuccess runs only if the request succeeded. See Invalidations from Mutations.
Return the invalidateQueries promise from onSuccess if you want the mutation to stay pending until the refetch finishes. For instant feedback, update the cache by hand with setQueryData instead.