Delete in React.js CRUD Operations

Introduction

In my previous article, I explored how the 'Update' operation plays a crucial role in maintaining the precision and relevance of data within a React.js application. This step-by-step guide, enriched with real-world examples, empowers developers to seamlessly integrate edit functionalities into their applications, along with the transmission of form data via HTTP PUT using Axios. The goal is to ensure a smooth and user-friendly experience within React applications.

Introduction of Delete in CRUD

Delete" refers to removing or deleting a particular piece of data from your application's state or server. CRUD operations are fundamental actions performed on data in a system.

Student data

Picture 1. Student management system Delete operation.

Student management system

Picture 2.  This table view contains two buttons 'Edit' and 'Delete.' 

Let’s start the Delete Action step by step

Step 1. Go to the student.js page Delete the Operation Function.

Create an arrow function as handleClickDelete. This function takes a parameter, row_id.

  const handleClickDelete = async (row_id) => { }

We call other functions or methods inside the 'handleClickDelete' function.

1. Confirmation Dialog

    const userConfirmed = window.confirm(
      "Are you sure you want to delete this record?"
    );

The window. confirm function displays a browser-level confirmation dialog with the specified message. The user's response is stored in the userConfirmed variable, which is a boolean indicating whether the user clicked "OK" or "Cancel."

2. Delete Record

   if (userConfirmed) {
    const response = await axios
      .delete(`http://localhost:5000/api/student/${row_id}`)
      .then((response) => {
        console.log("Record Deleted:", response.data);
      })
      .catch((error) => {
        console.error("Error >>>>:", error);
      });
    }

If the user confirms the deletion (userConfirmed is true), an asynchronous Axios DELETE request is made to the specified API endpoint (http://localhost:5000/api/student/${row_id}). The response is logged if successful, and any errors are caught and logged.

3. User Cancelled

else {
      // If the user cancels, you can provide feedback or take other actions
      console.log("Delete operation canceled by the user.");
    }

If the user cancels the deletion (userConfirmed is false), a message is logged to the console indicating that the delete operation was canceled by the user.

4. Trigger Re-fetch of Data

setFormSubmitted((prev) => prev + 1);

Regardless of whether the deletion was confirmed or canceled, the setFormSubmitted function is called to trigger a re-fetch of data. This is done by updating the FormSubmitted state variable. The component has a useEffect hook that listens for changes to FormSubmitted and re-fetches the student data accordingly.

 const handleClickDelete = async (row_id) => {
    // Display a confirmation dialog
    const userConfirmed = window.confirm(
      "Are you sure you want to delete this record?"
    );
    if (userConfirmed) {
    const response = await axios
      .delete(`http://localhost:5000/api/student/${row_id}`)
      .then((response) => {
        console.log("Record edited:", response.data);
      })
      .catch((error) => {
        console.error("Error >>>>:", error);
      });
    }else {
      // If the user cancels, you can provide feedback or take other actions
      console.log("Delete operation canceled by the user.");
    }
    setFormSubmitted((prev) => prev + 1);
  };

The deletion of a student record, providing a confirmation dialog for the user and taking appropriate actions based on their response. After the delete operation, it triggers a re-fetch of data to update the component's state.

Step 2. Rendered Component.

The Student component's render method returns JSX with a heading and the DataTable component, passing down data, handleClickEdit and handleClickDelete as props.

 return (
    <div className="App">
      <h1> Student Management System</h1>
      <MyForm editID={editID} setFormSubmitted={setFormSubmitted} />
      <DataTable
        data={data}
        handleClickEdit={handleClickEdit}
        handleClickDelete={handleClickDelete}
      />
    </div>
  );

Step 3. Go to the tabel.js page and add this destructuring parameter.

const Table = ({ data, handleClickEdit, handleClickDelete }) => {}

Go to the Delete Button and create an Onclick function

<button
size="small"
variant="outlined"
onClick={() => handleClickDelete(row._id)} >
 Delete
</button>

When the delete button is clicked, it triggers the handleClickDelete function with the row._id as an argument. The specific behavior of this code depends on the implementation of the handleClickDelete function and the context in which this button is used within the React application.

Demo

When I click the delete button, a dialog box will appear with two buttons: OK and Cancel. Clicking the OK button will delete the selected record from the database while clicking the Cancel button will cancel the action.

Cancel button

Cancel

Picture 3. Clicking the Cancel button will cancel the action.

OK button

Ok Button

Picture 4. Clicking the Cancel button will cancel the action.

Headers

Picture 5. Successfully deleted the record by the ID 65891ef252a0131af4c0aab5

Summary

The article also includes a demonstration of the implemented 'Delete' operation in a Student Management System, showcasing a dialog box with 'OK' and 'Cancel' buttons. Clicking 'OK' successfully deletes the selected record from the database, while clicking 'Cancel' cancels the action.

Finally, the article provides insight into integrating the 'Delete' functionality into the rendered component, demonstrating how to pass down the necessary data and functions as props to child components.

This concludes the discussion on CRUD operations in this article, where I covered Create, Read, Update, and Delete operations using a Node.js API. Additionally, I have addressed the following topics in separate articles:   

  1. Update in React.js CRUD Operations
  2. Create in React.js CRUD Operations
  3. Read in React.js CRUD Operations
  4. MVC Architecture With Node.js CRUD Application [Node.js-Express-MongoDB]

I believe these articles will be beneficial for individuals who are beginning their journey into MERN stack development at the beginner level, allowing them to learn and enjoy the process.


Adelanka (PVT) LTD
Globally based Software Developing & Data Processing Company