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 Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: