The basic guide for React Query useMutation hook

React Query is a popular library for fetching, caching, and updating asynchronous data in React applications. It provides a number of hooks, including useMutation that allows you to perform mutations (i.e., update data) on a server and automatically update your UI with the results.

Example

In order to use the useMutation hook, you first need to install React Query and add it to your React project. You can do this with the following command:

$ npm i @tanstack/react-query
# or
$ pnpm add @tanstack/react-query
# or
$ yarn add @tanstack/react-query

Once you have React Query installed, you can import the useMutation hook from the @tanstack/react-query package and use it in your functional component.

Here’s an example of how you might use useMutation to add a new post:

import React from "react";
import ReactDOM from "react-dom/client";
import {
  QueryClient,
  QueryClientProvider,
  useMutation
} from "@tanstack/react-query";

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <AddPostComponent />
    </QueryClientProvider>
  );
}

function AddPostComponent() {
  const { mutate, isLoading, error } = useMutation(
    (post) =>
      fetch("https://jsonplaceholder.typicode.com/posts", {
        method: "POST",
        body: JSON.stringify(post),
        headers: {
          "Content-type": "application/json; charset=UTF-8"
        }
      }),
    {
      onSuccess: async (data) => {
        alert("Post added successfully: " + JSON.stringify(await data.json()));
      },
      onError: (error) => {
        console.log(error);
      }
    }
  );

  return (
    <div>
      {isLoading ? (
        <div>Adding Post...</div>
      ) : (
        <button
          onClick={() =>
            mutate({
              title: "foo",
              body: "bar",
              userId: 1
            })
          }
        >
          Add Post
        </button>
      )}
      {error && <div>An error occurred: {error.message}</div>}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.createRoot(rootElement).render(<App />);

In this example, the useMutation hook is called with a function that performs the mutation (i.e., sends a POST request to the /posts endpoint) and an object with an onSuccess callback that shows an alert with the new data (at this point you can update the UI).

The hook call returns an object, some of the object properties we can extract them as the following:

const { mutate, isLoading, error } = useMutation....

mutate function is a function that you can call to perform the mutation.

isLoading and error are properties that include information about the current state of the mutation (e.g., whether it is loading, if there was an error, etc.).

When the component renders, the useMutation hook will return a function that you can call to add a new post. When the user clicks the “Add post” button, the mutate function will be called with the new post data, and React Query will automatically handle sending the request to the server, updating the cache with the latest data, and calling the onSuccess callback to update the UI.

In a summary React Query useMutation hook is a powerful tool for managing asynchronous data in your React applications. It makes it easy to perform mutations and automatically update your UI with the results, without having to worry about managing the details of fetching, caching, and updating data.


Related Posts

How to remove highcharts.com credits link

How to remove highcharts.com credits link

Highcharts is a popular JavaScript charting library that offers a wide range of interactive and customizable charts for developers. However, if you’re using the free version of…

Highcharts Place text in the center of a pie chart

Highcharts Place text in the center of a pie chart

To place text in the center of a pie chart in Highcharts, you can use the chart.renderer object to create a custom label and position it in…

Test design breakpoints using jest and react-testing-library

Test responsive design using jest and react-testing-library

Testing design breakpoints in React applications is an important aspect of front-end development. It ensures that the components look and behave as expected on different screen sizes….

Testing React-Query with Jest and React-testing-library

Testing React-Query with Jest and React-testing-library

Introduction In this article we will cover the basic usage of testing useQuery hook from tanstack/react-query library, along with how to test it using jest and react-testing-library….

Highcharts How To Change Series Color with examples

Highcharts How To Change Series Color with examples

To change the color of a series in Highcharts, there are a set of options we are going to discover in this article. Option 1: Using the…

A quick introduction to Javascript shadow DOM

A quick introduction to Javascript shadow DOM

Introduction JavaScript Shadow DOM is a powerful tool for creating isolated and reusable components in web development. It allows developers to create custom elements with their own…

Leave a Reply

%d bloggers like this: