0Pricing
React Academy · Lesson

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()),
});

All lessons in this course

  1. Setting Up React Query & QueryClient
  2. Caching, Stale Time & Background Refetching
  3. Mutations with useMutation
  4. Infinite Scroll & Pagination with useInfiniteQuery
← Back to React Academy