React Query Handle Delete Request with useMutation Tutorial

Last updated on: by Digamber

React Query Delete Mutation Query example. In this tutorial, we will teach you how to use React Query useMutation hook to delete data from the database in React JS application.

Mutations provide a simple ecosystem that helps to perform create, edit and delete data in contrast with server-side effects. To trigger the delete HTTP request, we will also need an Axios client.

We will start with creating a basic React application and install React Query and Axios packages using npm. We will use a function class or the functional component to perform the server-side calls.

To create a delete request requires to configure the React Query module in React. We will make you familiar with the entire process through this guide. Also, have a look at how to gain access to React query useMutation hook.

How to Make Delete Request in React with React Query Mutation

  • Step 1: Build React Project
  • Step 2: Add Axios & React Query
  • Step 3: Register Bootstrap
  • Step 4: Setting Up React-Query
  • Step 5: Create New Component
  • Step 6: Build Backend Server
  • Step 7: Delete Data from Database
  • Step 8: Register New Component
  • Step 9: View App on Browser

Build React Project

Open the console, use the following command to create and the enter into the app folder.

npx create-react-app react-blog-app
cd react-blog-app

Add Axios & React Query

We are now in the project folder, next run the command to install axios and React query simultaneously.

npm install @tanstack/react-query axios

Register Bootstrap

We are installing bootstrap library in React so that we can use it’s UI components to create the basic UI in React.

npm i bootstrap

The next step is to add or import bootstrap CSS in the src/App.js file.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
function App() {
  return <div></div>;
}
export default App;

Setting Up React-Query

React query won’t work unless we register certain react-query modules in the App.js file.

Make sure to replace the current code with the following code.

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// Create a client
const queryClient = new QueryClient();
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
);

Create New Component

Head into the src/ folder, create a new folder, name it components/ then create and the given code to the Users.js function file.

import React from 'react'
function Users() {
  return (
    <div>Users page</div>
  )
}
export default Users

Build Backend Server

We need to globally install the json-server package in React, therefore execute the suggested command.

sudo npm install -g json-server

Now, we need a file that is the pivotal point to store the Fake API data, create the db.json file at the root of your React project.

{
  "posts": [
    {
      "id": 1,
      "title": "Sunt aut facere repellat provident.",
      "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },
    {
      "id": 3,
      "title": "Ea molestias quasi exercitationem.",
      "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
    },
    {
      "id": 4,
      "title": "Eum et est occaecati",
      "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
    },
    {
      "id": 5,
      "title": "Nesciunt quas odio.",
      "body": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
    }
  ]
}

Run the json server from the terminal with the help of the given command.

json-server --watch db.json --port 3004

Delete Data from Database

We are first fetching the data from the database that we created previously using the useQuery hook.

Use the useMutation hook to delete the data from the database; after you click on delete, make sure to refresh the page to see the delete data effect.

Insert the following code to the components/Users.js file.

import React from "react";
import axios from "axios";
import { useQuery, useMutation } from "@tanstack/react-query";
async function getPosts() {
  const { data } = await axios.get("http://localhost:3004/posts");
  return data;
}
function Users() {
  const deletePost = useMutation((id) => {
    return axios.delete(`http://localhost:3004/posts/${id}`);
  });
  const { isLoading, isError, error, data } = useQuery(["posts"], getPosts);
  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (isError) {
    return <div>Error! {error.message}</div>;
  }
  return (
    <ul className="list-group">
      {data.map((res, i) => {
        return (
          <li className="list-group-item mb-4" key={i}>
            <h3>{res.title}</h3>
            <p className="mb-3">{res.body}</p>
            <button
              type="button"
              className="btn btn-outline-danger"
              onClick={() => deletePost.mutate(res.id)}
            >
              Delete
            </button>
          </li>
        );
      })}
    </ul>
  );
}
export default Users;

Register New Component

In order to see the delete request in action; make sure to register the new component in the App.js file.

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import Users from "./components/Users";
function App() {
  return (
    <div className="container mt-5">
      <h2 className="mb-4">React Query useMutation Hook Delete Data from Database Example</h2>
      <Users />
    </div>
  );
}
export default App;

View App on Browser

We eventually reached the final destination. Now, we will start the React server with the following command open the app on the browser.

npm start
http://localhost:3000

React Query Handle Delete Request with useMutation Tutorial

Conclusion

In this post, we have seen how to efficiently use React Query to perform a Delete Mutation request using the useMutation hook in React web application.

Also, how to set up React query in React app using react query npm module.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.