Skip to content
react

How to call HTTP delete using axios in React

Feb 22, 2023Abhishek EH2 Min Read
How to call HTTP delete using axios in React

In my previous article, I explained using axios in react. In this article, we will see how to call a delete API from react application using axios.

Project setup

First create a react app using the following command:

1npx create-react-app react-axios-delete

Now install axios using the following command:

1npm i axios

In App.js, add a delete button and bind a handler to it as shown below:

App.js
1function App() {
2 const deleteHandler = () => {}
3
4 return (
5 <div>
6 <button onClick={deleteHandler}>Delete</button>
7 </div>
8 )
9}
10
11export default App

Deleting using axios

We will be using the JSONPlaceholder API for demonstrating the delete functionality.

App.js
1import axios from "axios"
2
3function App() {
4 const deleteHandler = () => {
5 axios
6 .delete("https://jsonplaceholder.typicode.com/posts/1")
7 .then(response => {
8 console.log("deleted successfully!")
9 })
10 }
11
12 return (
13 <div>
14 <button onClick={deleteHandler}>Delete</button>
15 </div>
16 )
17}
18
19export default App

You can call the delete API as shown above.

Deleting using async await

If you want to use async await syntax, you can use the following code:

1const deleteHandler = async () => {
2 const response = await axios.delete(
3 "https://jsonplaceholder.typicode.com/posts/1"
4 )
5 console.log("deleted successfully!")
6}

Passing header while deleting

If you need to pass any headers to the delete request, you can do it as shown below:

1const deleteHandler = () => {
2 const headers = { foo: "bar" }
3 axios
4 .delete("https://jsonplaceholder.typicode.com/posts/1", { headers })
5 .then(response => {
6 console.log("deleted successfully!")
7 })
8}

Error handling which calling delete API

You can add a catch callback to handle errors:

1const deleteHandler = () => {
2 const headers = { foo: "bar" }
3 axios
4 .delete("https://jsonplaceholder.typicode.com/posts/1", { headers })
5 .then(response => {
6 console.log("deleted successfully!")
7 })
8 .catch(error => {
9 console.log("Something went wrong", error)
10 })
11}

If you are using async-await syntax, then you can wrap the code inside a try-catch block:

1const deleteHandler = async () => {
2 try {
3 const response = await axios.delete(
4 "https://jsonplaceholder.typicode.com/posts/1"
5 )
6 console.log("deleted successfully!")
7 } catch (error) {
8 console.log("Something went wrong", error)
9 }
10}

Do follow me on twitter where I post developer insights more often!

© 2024 CodingDeft.Com