How to Send Axios Delete to the Backend ReactJS in JavaScript


What is Send Axios Delete?

Deleting data from a backend using ReactJS and Axios can be a challenging task. However, with the right approach and knowledge, you can easily achieve this task. In this article, we'll explore how to send an Axios delete request to the backend in ReactJS using JavaScript. We'll cover two different approaches with code and explanations, as well as two working examples. So, let's dive in!

Algorithm

To commence our discourse, it is of utmost importance to apprehend the procedure for transmitting an Axios obliteration entreaty to the back end when utilizing ReactJS. Here are the steps −

  • Incorporate Axios − It is imperative to include Axios, a prevalent library exploited for fabricating HTTP petitions.

  • Establish a purge entreaty − Subsequently, you will initiate a purge entreaty utilizing Axios. This entails stipulating the Uniform Resource Locator (URL), the headers (if any), and any data that necessitates transmission to the server.

  • Dispatch the entreaty − In conclusion, you will transmit the purge entreaty to the server utilizing Axios.

Approach 1: Using Axios Delete Method

The first approach involves using the Axios delete method. Here's the code −

import axios from 'axios';
const deleteData = async (id) => {
   try {
      const response = await axios.delete(`https://example.com/api/data/${id}`);
      console.log(response.data);
   } catch (error) {
      console.error(error);
   }
};

In the above code, we've defined a function called deleteData that takes an id parameter. Inside the function, we use the Axios delete method to send a delete request to the server. The URL we're targeting includes the id parameter, which represents the data we want to delete. We then log the response data to the console if the request is successful. If an error occurs, we log the error to the console.

Example

In this example, we'll create a delete button that deletes data when clicked. Here's the code −

import React from 'react';
import axios from 'axios';
const DeleteButton = ({ id }) => {
   const handleDelete = async () => {
      try {
         const response = await axios.delete(`https://example.com/api/data/${id}`);
         console.log(response.data);
      } catch (error) {
         console.error(error);
      }
   };
   return (
      <button onClick={handleDelete}>
         Delete
      </button>
   );
};
export default DeleteButton;

The aforementioned code illustrates a component titled DeleteButton that allows the acceptance of an id prop to establish the delete request URL. On clicking the delete button, the handleDelete function is invoked, which utilizes the Axios delete approach to dispatch a delete request to the server, specifying the relevant id. Upon a successful request, the response data is recorded in the console. Conversely, if any error ensues, the error is also recorded in the console.

Approach 2: Using Axios Request Method

The alternative method necessitates the utilization of the Axios solicitation procedure accompanied by the 'delete' property setting for the method attribute. The following is the corresponding code snippet −

// Import Axios library
const axios = require('axios');

// Define a function to delete data
async function deleteData(id) {
   try {
   
      // Make a DELETE request to the API with the given ID
      const response = await axios({
         url: 'https://example.com/api/data/' + id,
         method: 'delete'
      });
      console.log(response.data);
   } catch (error) {
   
      // Log any errors that occur
      console.error(error);
   }
}

In this code, we've defined the same deleteData function as in the first approach. However, instead of using the Axios delete method, we use the Axios request method with the method property set to 'delete'. We then log the response data to the console if the request is successful. If an error occurs, we log the error to the console.

Now that we've covered the two approaches with code and explanations, let's look at two working examples of how to send an Axios delete request to the backend in ReactJS.

Example: Delete Confirmation Modal

In this example, we'll create a delete confirmation modal that deletes data when confirmed. Here's the code.

import React, { useState } from 'react';
import axios from 'axios';
const DeleteConfirmationModal = ({ id }) => {
   const [isOpen, setIsOpen] = useState(false);
   const handleDelete = async () => {
      try {
         const response = await axios.delete(`https://example.com/api/data/${id}`);
         console.log(response.data);
      } catch (error) {
         console.error(error);
      }
      setIsOpen(false);
   };

   return (
      <>
      <button onClick={() => setIsOpen(true)}>
         Delete
      </button>
      {isOpen && (
         <div>
            <p>Are you sure you want to delete this data?</p>
            <button onClick={handleDelete}>
               Yes, delete it
            </button>
            <button onClick={() => setIsOpen(false)}>
               Cancel
            </button>
         </div>
      )}
      </>
   );
};

export default DeleteConfirmationModal;

Output

The above code contains a component named DeleteConfirmationModal, which accepts an id prop. When the delete button is clicked, a confirmation modal is presented. If the user confirms the deletion, the handleDelete function is executed. This function utilizes the Axios delete method to transmit a delete request to the server, specifying the id. Upon a successful request, the response data is logged to the console. Conversely, if any error ensues, the error is also recorded in the console. To conclude, the isOpen state is set to false, thereby closing the confirmation modal.

Conclusion

In this article, we explored how to send an Axios delete request to the backend in ReactJS using JavaScript. We covered two different approaches with code and explanations, as well as two working examples. By following the steps outlined in this article, you should be able to easily delete data from a backend using ReactJS and Axios.

Updated on: 17-Apr-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements