React RTK Query Delete Data with Api Slice Tutorial

Last updated on: by Digamber

This extensive guide will teach you how to get and delete data objects from the database in React application using React Redux RTK Query endpoints and REST APIs.

We will develop a simple blog app, and this app allows users to add a post, fetch all posts from json server, and delete a post using an id from the server in React app.

How to Delete Data in React using RTK Delete Query Endpoint

  • Step 1: Download React Project
  • Step 2: Install Redux Modules
  • Step 3: Create JSON Server
  • Step 4: Create Get and Delete Endpoints
  • Step 5: Update ApiSlice in Redux Store
  • Step 6: Delete Post with RTK Hook
  • Step 7: Add Component in App Js File
  • Step 8: Run React Server

Download React Project

Open the terminal, type the command then execute command to download a new react app.

npx create-react-app react-rtk-query-delete-example

Install Redux Modules

In this step, we are going to install the important packages using the given command.

npm install react-redux @reduxjs/toolkit bootstrap

Create JSON Server

We are going to create a backend server using the json-server module and run the command to install the package.

npm install -g json-server

Next, you have to create the db.json file and add the code into the file.

{
  "posts": [
    {
      "id": 1,
      "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
      "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    }
  ]
}

You are now ready to run the server, execute the command.

json-server --watch db.json

Create Get and Delete Endpoints

In this step, you need to go to src/ folder, create ‘features’ folder, now make the ‘api’ folder. Next, you have to add given code in features/api/apiSlice.js file.

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const apiSlice = createApi({
  reducerPath: 'apiSlice',
  baseQuery: fetchBaseQuery({
    baseUrl: 'http://localhost:3000',
  }),
  tagTypes: ['Post'],
  endpoints: (builder) => ({
    getPosts: builder.query({
      query: () => '/posts',
      providesTags: ['Post'],
    }),
    addNewPost: builder.mutation({
      query: (payload) => ({
        url: '/posts',
        method: 'POST',
        body: payload,
        headers: {
          'Content-type': 'application/json; charset=UTF-8',
        },
      }),
      invalidatesTags: ['Post'],
    }),
    deletePost: builder.mutation({
      query: (id) => ({
        url: `/posts/${id}`,
        method: 'DELETE',
        credentials: 'include',
      }),
      invalidatesTags: ['Post'],
    }),
  }),
})
export const {
  useGetPostsQuery,
  useAddNewPostMutation,
  useDeletePostMutation,
} = apiSlice

Update ApiSlice in 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 { apiSlice } from '../features/api/apiSlice'
export const store = configureStore({
  reducer: {
    [apiSlice.reducerPath]: apiSlice.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware),
})
setupListeners(store.dispatch)

Now, you have to head over to index.js file here you have to import and set the ApiProvider around App component.

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import { ApiProvider } from '@reduxjs/toolkit/dist/query/react'
import { apiSlice } from './features/api/apiSlice'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
  <React.StrictMode>
    <ApiProvider api={apiSlice}>
      <App />
    </ApiProvider>
  </React.StrictMode>,
)

Delete Post with RTK Hook

You have to create the features/posts/PostsList.js file and in this file we will import the useGetPostsQuery, useAddNewPostMutation, and useDeletePostMutation hooks and dispatch the action to fetch, create and delete the data from the database.

import React from 'react'
import {
  useGetPostsQuery,
  useAddNewPostMutation,
  useDeletePostMutation,
} from '../api/apiSlice'
const PostCard = ({ content }) => {
  const [deletePost, response] = useDeletePostMutation()
  return (
    <div className="col-lg-4 mb-3 d-flex align-items-stretch" key={content.id}>
      <div className="card alert alert-secondary">
        <div className="card-body d-flex flex-column">
          <h5 className="card-title">{content.title}</h5>
          <p className="card-text">{content.body}</p>
          <button
            onClick={() => deletePost(content.id)}
            class="btn btn-outline-danger"
          >
            Remove
          </button>
        </div>
      </div>
    </div>
  )
}
function PostsList() {
  let formSubmitError
  const [addNewPost, response] = useAddNewPostMutation()
  const [postForm, setPostForm] = React.useState('Submit')
  const onSubmit = (e) => {
    e.preventDefault()
    const { title, body } = e.target.elements
    let formData = {
      title: title.value,
      body: body.value,
    }
    addNewPost(formData)
      .unwrap()
      .then(() => {})
      .then((error) => {
        console.log(error)
      })
  }
  const {
    data: posts,
    isLoading: isGetLoading,
    isSuccess: isGetSuccess,
    isError: isGetError,
    error: getError,
  } = useGetPostsQuery({ refetchOnMountOrArgChange: true })
  let postContent
  if (isGetLoading) {
    postContent = (
      <div className="d-flex justify-content-center">
        <div className="spinner-border" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    )
  } else if (isGetSuccess) {
    postContent = posts.map((item) => {
      return <PostCard content={item} key={item.id} />
    })
  } else if (isGetError) {
    postContent = (
      <div className="alert alert-danger" role="alert">
        {getError}
      </div>
    )
  }
  return (
    <div className="row">
      {formSubmitError}
      <div className="col-md-4 offset-md-*">
        <form onSubmit={onSubmit}>
          <div className="mb-3">
            <label className="form-label">
              <strong>Enter Title</strong>
            </label>
            <input type="text" className="form-control" id="title" />
          </div>
          <div className="mb-3">
            <label className="form-label">
              <strong>Enter content</strong>
            </label>
            <textarea className="form-control" id="body" rows="3"></textarea>
          </div>
          <div className="d-grid">
            <button className="btn btn-success" type="submit">
              {postForm}
            </button>
          </div>
        </form>
      </div>
      <div className="col-lg-8">
        <div className="row">{postContent}</div>
      </div>
    </div>
  )
}
export default PostsList

Add Component in App Js File

Open the App.js file, in this file we will import and define the PostList component.

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
import './App.css'
import PostsList from './features/posts/PostsList'
function App() {
  return (
    <div className="container">
      <div className="d-flex border-bottom pt-2 pb-2 mb-5">
        <div className="p-2 flex-grow-1 text-center">
          <h2>React RTK Query Delete Data with Id Example</h2>
        </div>
      </div>
      <PostsList />
    </div>
  )
}
export default App

Run React Server

In this last step, you will run the following command to run the react server.

npm start

React RTK Query Delete Data with Api Slice Tutorial

Conclusion

In this guide, we have profoundly explained how to set up the Redux store in React app. How to create api slice using Redux Toolkit, connect api slice to redux store and display all posts and auto refetch posts. Create and most importantly, remove or delete post objects from the database.

Download Source code.

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.