Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Using useMutation for Server Updates | Mutations and Updating Data
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
TanStack Query Server State Management in React

bookUsing useMutation for Server Updates

When you need to send data-changing requests—like creating, updating, or deleting records—to your server from a React component, TanStack Query provides the useMutation hook. Unlike useQuery, which is designed for fetching and caching data, useMutation is tailored for operations that alter data. The basic syntax for useMutation involves passing a mutation function, which is responsible for carrying out the server request, and optionally providing configuration options for handling different stages of the mutation process.

The typical usage looks like this:

const mutation = useMutation({
  mutationFn,
  onMutate,
  onSuccess,
  onError,
  onSettled,
});

Here's what each part means:

  • mutationFn: the function that performs the server update and returns a promise;
  • onMutate: an optional callback that runs right before the mutation function executes;
  • onSuccess: an optional callback that runs after a successful mutation;
  • onError: an optional callback that runs if the mutation fails;
  • onSettled: an optional callback that runs after the mutation finishes, whether it succeeds or fails.

The useMutation hook returns an object containing methods and state related to the mutation, such as:

  • mutate: a function you call to execute the mutation;
  • isLoading: indicates if the mutation is in progress;
  • isSuccess: indicates if the mutation completed successfully;
  • isError: indicates if the mutation failed;
  • data: contains the response from the server (if successful);
  • error: contains error information (if failed).

To see how this works in practice, imagine you want to add a new user to your database from a form input. You would define a mutation function that sends a POST request to your server, and then use useMutation to manage the process and handle the result.

First, define your mutation function:

async function createUser(newUser) {
  const response = await fetch("/api/users", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(newUser),
  });

  if (!response.ok) {
    throw new Error("Failed to create user");
  }

  return response.json();
}

Then, use useMutation in your component:

const { mutate, isPending, isSuccess, isError, data, error } = useMutation({
  mutationFn: createUser,
  onSuccess: (data) => {
    alert("User created: " + data.name);
  },
  onError: (error) => {
    alert("Error: " + error.message);
  },
});

When the user submits the form, call mutate with the new user data:

function handleSubmit(newUser) {
  mutate(newUser);
}

This setup not only sends the request to the server, but also allows you to react to the outcome—showing messages, updating the UI, or triggering other side effects.

Understanding the mutation lifecycle is essential for creating a responsive and robust user experience. TanStack Query provides four key lifecycle callbacks you can use to hook into different stages of the mutation process:

  • onMutate: runs just before the mutation function is called. This is useful for updating the UI optimistically, such as showing a loading spinner or temporarily updating data before the server confirms the change;
  • onSuccess: runs only if the mutation succeeds. Use this to update the UI with the server's response, show success notifications, or invalidate related queries to trigger refetching;
  • onError: runs if the mutation fails. Use this to revert optimistic updates, display error messages, or log errors;
  • onSettled: runs after the mutation completes, regardless of whether it succeeded or failed. This is helpful for cleanup tasks or resetting UI state.
question mark

Which mutation lifecycle callback should you use to update the UI after a successful mutation?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 1

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

bookUsing useMutation for Server Updates

Свайпніть щоб показати меню

When you need to send data-changing requests—like creating, updating, or deleting records—to your server from a React component, TanStack Query provides the useMutation hook. Unlike useQuery, which is designed for fetching and caching data, useMutation is tailored for operations that alter data. The basic syntax for useMutation involves passing a mutation function, which is responsible for carrying out the server request, and optionally providing configuration options for handling different stages of the mutation process.

The typical usage looks like this:

const mutation = useMutation({
  mutationFn,
  onMutate,
  onSuccess,
  onError,
  onSettled,
});

Here's what each part means:

  • mutationFn: the function that performs the server update and returns a promise;
  • onMutate: an optional callback that runs right before the mutation function executes;
  • onSuccess: an optional callback that runs after a successful mutation;
  • onError: an optional callback that runs if the mutation fails;
  • onSettled: an optional callback that runs after the mutation finishes, whether it succeeds or fails.

The useMutation hook returns an object containing methods and state related to the mutation, such as:

  • mutate: a function you call to execute the mutation;
  • isLoading: indicates if the mutation is in progress;
  • isSuccess: indicates if the mutation completed successfully;
  • isError: indicates if the mutation failed;
  • data: contains the response from the server (if successful);
  • error: contains error information (if failed).

To see how this works in practice, imagine you want to add a new user to your database from a form input. You would define a mutation function that sends a POST request to your server, and then use useMutation to manage the process and handle the result.

First, define your mutation function:

async function createUser(newUser) {
  const response = await fetch("/api/users", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(newUser),
  });

  if (!response.ok) {
    throw new Error("Failed to create user");
  }

  return response.json();
}

Then, use useMutation in your component:

const { mutate, isPending, isSuccess, isError, data, error } = useMutation({
  mutationFn: createUser,
  onSuccess: (data) => {
    alert("User created: " + data.name);
  },
  onError: (error) => {
    alert("Error: " + error.message);
  },
});

When the user submits the form, call mutate with the new user data:

function handleSubmit(newUser) {
  mutate(newUser);
}

This setup not only sends the request to the server, but also allows you to react to the outcome—showing messages, updating the UI, or triggering other side effects.

Understanding the mutation lifecycle is essential for creating a responsive and robust user experience. TanStack Query provides four key lifecycle callbacks you can use to hook into different stages of the mutation process:

  • onMutate: runs just before the mutation function is called. This is useful for updating the UI optimistically, such as showing a loading spinner or temporarily updating data before the server confirms the change;
  • onSuccess: runs only if the mutation succeeds. Use this to update the UI with the server's response, show success notifications, or invalidate related queries to trigger refetching;
  • onError: runs if the mutation fails. Use this to revert optimistic updates, display error messages, or log errors;
  • onSettled: runs after the mutation completes, regardless of whether it succeeded or failed. This is helpful for cleanup tasks or resetting UI state.
question mark

Which mutation lifecycle callback should you use to update the UI after a successful mutation?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 1
some-alt