Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Using useMutation for Data Changes | Updating Data and Advanced Query Features
React Query Essentials

bookUsing useMutation for Data Changes

When you need to change data on your serverβ€”such as creating, updating, or deleting itemsβ€”React Query provides the useMutation hook. Unlike useQuery, which is designed for fetching and caching data, useMutation is focused on performing side-effect operations that alter data. The useMutation hook accepts a function that performs the mutation (such as a POST, PUT, or DELETE request), and returns an object containing useful properties and methods for tracking and handling the mutation's status.

The primary parameters for useMutation include the mutation function itself, and optionally, configuration options like onSuccess or onError callbacks. The return value is an object with properties such as mutate, mutateAsync, isLoading, isError, isSuccess, and error. These help you control the mutation process and provide feedback to users.

Suppose you want to submit a form that creates a new post. You can use useMutation to handle the form submission and update your UI based on the mutation state. Here is a typical example:

import { useMutation } from "@tanstack/react-query";

function createPost(newPost) {
  return fetch("/api/posts", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(newPost),
  }).then((res) => res.json());
}

function NewPostForm() {
  const mutation = useMutation({
    mutationFn: createPost,
  });

  function handleSubmit(event) {
    event.preventDefault();
    const form = event.target;
    const post = {
      title: form.elements.title.value,
      content: form.elements.content.value,
    };
    mutation.mutate(post);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="title" placeholder="Title" />
      <textarea name="content" placeholder="Content" />
      <button type="submit" disabled={mutation.isLoading}>
        Submit
      </button>
      {mutation.isLoading && <p>Saving...</p>}
      {mutation.isError && <p>Error: {mutation.error.message}</p>}
      {mutation.isSuccess && <p>Post created!</p>}
    </form>
  );
}

The mutation object returned by useMutation provides several properties that let you track the status of your mutation. The isLoading property is true while the mutation is in progress, allowing you to show a loading indicator or disable the submit button. If the request fails, isError is set to true, and you can access the error information via the error property. When the mutation completes successfully, isSuccess becomes true, so you can show a confirmation message or trigger additional actions. These states help you provide clear feedback to users and handle errors gracefully during create, update, or delete operations.

question mark

Which scenario best describes when you should use the useMutation hook in React Query?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 1

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Suggested prompts:

Can you explain how to handle errors with useMutation in more detail?

What are some common use cases for useMutation besides creating posts?

How can I reset the mutation state after a successful submission?

bookUsing useMutation for Data Changes

Swipe to show menu

When you need to change data on your serverβ€”such as creating, updating, or deleting itemsβ€”React Query provides the useMutation hook. Unlike useQuery, which is designed for fetching and caching data, useMutation is focused on performing side-effect operations that alter data. The useMutation hook accepts a function that performs the mutation (such as a POST, PUT, or DELETE request), and returns an object containing useful properties and methods for tracking and handling the mutation's status.

The primary parameters for useMutation include the mutation function itself, and optionally, configuration options like onSuccess or onError callbacks. The return value is an object with properties such as mutate, mutateAsync, isLoading, isError, isSuccess, and error. These help you control the mutation process and provide feedback to users.

Suppose you want to submit a form that creates a new post. You can use useMutation to handle the form submission and update your UI based on the mutation state. Here is a typical example:

import { useMutation } from "@tanstack/react-query";

function createPost(newPost) {
  return fetch("/api/posts", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(newPost),
  }).then((res) => res.json());
}

function NewPostForm() {
  const mutation = useMutation({
    mutationFn: createPost,
  });

  function handleSubmit(event) {
    event.preventDefault();
    const form = event.target;
    const post = {
      title: form.elements.title.value,
      content: form.elements.content.value,
    };
    mutation.mutate(post);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="title" placeholder="Title" />
      <textarea name="content" placeholder="Content" />
      <button type="submit" disabled={mutation.isLoading}>
        Submit
      </button>
      {mutation.isLoading && <p>Saving...</p>}
      {mutation.isError && <p>Error: {mutation.error.message}</p>}
      {mutation.isSuccess && <p>Post created!</p>}
    </form>
  );
}

The mutation object returned by useMutation provides several properties that let you track the status of your mutation. The isLoading property is true while the mutation is in progress, allowing you to show a loading indicator or disable the submit button. If the request fails, isError is set to true, and you can access the error information via the error property. When the mutation completes successfully, isSuccess becomes true, so you can show a confirmation message or trigger additional actions. These states help you provide clear feedback to users and handle errors gracefully during create, update, or delete operations.

question mark

Which scenario best describes when you should use the useMutation hook in React Query?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 1
some-alt