Table of Contents
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:
1function App() {2 const deleteHandler = () => {}34 return (5 <div>6 <button onClick={deleteHandler}>Delete</button>7 </div>8 )9}1011export default App
Deleting using axios
We will be using the JSONPlaceholder API for demonstrating the delete functionality.
1import axios from "axios"23function App() {4 const deleteHandler = () => {5 axios6 .delete("https://jsonplaceholder.typicode.com/posts/1")7 .then(response => {8 console.log("deleted successfully!")9 })10 }1112 return (13 <div>14 <button onClick={deleteHandler}>Delete</button>15 </div>16 )17}1819export 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 axios4 .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 axios4 .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}
If you have liked article, stay in touch with me by following me on twitter.
Leave a Comment