How to Delete Server Record with RTK Endpoint in React

React RTK Query DELETE Request example. This tutorial will cover how to create and use a GET and DELETE data endpoints using Redux RTK Query in React.

Managing states in React is challenging. Redux offers an easy way to tackle this problem. With, Its central state container, you can create any state through a slice and access it from anywhere in the app.

Making requests and receiving a response from servers contains a certain process — It can be hectic sometimes.

What if we told you? Redux can simplify your life with its data fetching and caching tool.

Display UI loader while loading data, avoid duplicate requests, and manage cache lifetime. Anything you can imagine, RTK Query will bring it to you!

Redux provides a separate tool RTK Query. It helps you limit writing excessive code for server communication.

React RTK Query Delete Request with React Redux Tutorial

  • Step 1: Build React App
  • Step 2: Install Essential Packages
  • Step 3: Build JSON Server
  • Step 4: Create APIs or Endpoints/li>
  • Step 5: Set Up Redux Store
  • Step 6: Fetch and Delete Record
  • Step 7: Register Component File
  • Step 8: Start Development Server

Build React App

First step is to open the terminal, type the command and execute the command to install a React app.

npx create-react-app react-demo

Install Essential Packages

This functionality requires installing third-party dependencies: use the command to add react-redux, bootstrap, and redux toolkit.

npm install react-redux bootstrap @reduxjs/toolkit

Build JSON Server

Now, you have to install the JSON server. This library helps you create a fake backend server that you use to mock the API.

npm install json-server -g

Make the db.json at the root of the React project and In this file define the given code.

{
  "users": [
    {
      "id": 1,
      "name": "Leanne Graham",
      "email": "lincere@april.biz"
    },
    {
      "id": 2,
      "name": "Ervin Howell",
      "email": "shanna@melissa.tv"
    },
    {
      "id": 3,
      "name": "Clementine Bauch",
      "email": "nathan@yesenia.net"
    }
  ]
}

Open the terminal, on the console type the command and then run the command.

json-server --watch db.json

Create APIs or Endpoints

The data fetching and caching logic is built on top of Redux Toolkit’s createSlice and createAsyncThunk APIs.

Hence, we need a separate file where we’ll write the logic to build the endpoints.

Create a features/dataSlice.js folder file, and insert the given code in the file.

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const dataSlice = createApi({
  reducerPath: "apiSlice",
  baseQuery: fetchBaseQuery({
    baseUrl: "http://localhost:3000",
  }),
  tagTypes: ["User"],
  endpoints: (builder) => ({
    getUsers: builder.query({
      query: () => "/users",
      providesTags: ["User"],
    }),
    deleteUser: builder.mutation({
      query: (id) => ({
        url: `/users/${id}`,
        method: "DELETE",
        credentials: "include",
      }),
      invalidatesTags: ["User"],
    }),
  }),
});

export const { useGetUsersQuery, useDeleteUserMutation } = dataSlice;

Set Up Redux Store

You require to create the app directory, make the store.js file in the app folder and add the provided code into the src/app/store.js file.

import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";
import { dataSlice } from "../features/dataSlice";

export const store = configureStore({
  reducer: {
    [dataSlice.reducerPath]: dataSlice.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(dataSlice.middleware),
});

setupListeners(store.dispatch);

Open the index.js file. Wrap the App component with ApiProvider; pass the dataSlice to api object.

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

import { ApiProvider } from "@reduxjs/toolkit/dist/query/react";
import { dataSlice } from "./features/dataSlice";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
  <React.StrictMode>
    <ApiProvider api={dataSlice}>
      <App />
    </ApiProvider>
  </React.StrictMode>
);

Fetch and Delete Record

Next, you have to make the components/Users.js folder and file. We’ll show the users list using Bootstrap, create the layout with Bootstrap UI components.

To get the data and delete the data in server use the useGetUsersQuery, and useDeleteUserMutation hooks.

import React from "react";
import { useGetUsersQuery, useDeleteUserMutation } from "../features/dataSlice";

const Card = ({ data }) => {
  const [deleteUser] = useDeleteUserMutation();

  return (
    <div className="col-lg-12 mb-2" key={data.id}>
      <div className="card">
        <div className="card-body">
          <h5 className="card-title">{data.name}</h5>
          <p className="card-text">{data.email}</p>
          <button
            onClick={() => deleteUser(data.id)}
            className="btn btn-sm btn-outline-danger"
          >
            Delete
          </button>
        </div>
      </div>
    </div>
  );
};

function Users() {
  const { data, isLoading, isSuccess, isError, error } = useGetUsersQuery({
    refetchOnMountOrArgChange: true,
  });

  let userData;

  if (isLoading) {
    userData = (
      <div className="d-flex justify-content-center">
        <div className="spinner-border">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  } else if (isSuccess) {
    userData = data.map((res) => {
      return <Card data={res} key={res.id} />;
    });
  } else if (isError) {
    userData = <div className="alert alert-danger">{error}</div>;
  }

  return <div>{userData}</div>;
}

export default Users;

Register Component File

We have built the feature, however if you start the app nothing will appear on the browser. Hence, import the Users component with bootstrap classes in src/App.js file.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import Users from "./components/Users";

function App() {
  return (
    <div className="container mt-5">
      <div className="row">
        <Users />
      </div>
    </div>
  );
}

export default App;

Start Development Server

We are finished with the functionalities; next, run the react app, and view it on the browser.

npm start

How to Delete Server Record with RTK Endpoint in React

Conclusion

RTK Query makes data fetching and caching amazingly uncomplicated. In this guide, we showed you how to delete the data on the server using the RTK Query endpoint.

You can have a look at the full code of this tutorial @GitHub.