Mutations with useMutation
Post data to APIs with useMutation, handle loading/error states, and invalidate queries on success.
Welcome
In this lesson you will use useMutation to post data to APIs, handle loading and error states, and invalidate stale queries after successful mutations.
useMutation Basics
Call useMutation with a mutationFn. It returns a mutate function and status properties. Call mutate() to trigger the operation.
import { useMutation } from '@tanstack/react-query';
const { mutate, isLoading, isError } = useMutation({
mutationFn: (newPost) => fetch('/api/posts', {
method: 'POST',
body: JSON.stringify(newPost),
}).then(r => r.json()),
});