DEV Community

Cover image for How to call HTTP delete using axios in React
collegewap
collegewap

Posted on • Originally published at codingdeft.com

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:

npx create-react-app react-axios-delete
Enter fullscreen mode Exit fullscreen mode

Now install axios using the following command:

npm i axios
Enter fullscreen mode Exit fullscreen mode

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

function App() {
  const deleteHandler = () => {}

  return (
    <div>
      <button onClick={deleteHandler}>Delete</button>
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Deleting using axios

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

import axios from "axios"

function App() {
  const deleteHandler = () => {
    axios
      .delete("https://jsonplaceholder.typicode.com/posts/1")
      .then(response => {
        console.log("deleted successfully!")
      })
  }

  return (
    <div>
      <button onClick={deleteHandler}>Delete</button>
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

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:

const deleteHandler = async () => {
  const response = await axios.delete(
    "https://jsonplaceholder.typicode.com/posts/1"
  )
  console.log("deleted successfully!")
}
Enter fullscreen mode Exit fullscreen mode

Passing header while deleting

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

const deleteHandler = () => {
  const headers = { foo: "bar" }
  axios
    .delete("https://jsonplaceholder.typicode.com/posts/1", { headers })
    .then(response => {
      console.log("deleted successfully!")
    })
}
Enter fullscreen mode Exit fullscreen mode

Error handling which calling delete API

You can add a catch callback to handle errors:

const deleteHandler = () => {
  const headers = { foo: "bar" }
  axios
    .delete("https://jsonplaceholder.typicode.com/posts/1", { headers })
    .then(response => {
      console.log("deleted successfully!")
    })
    .catch(error => {
      console.log("Something went wrong", error)
    })
}
Enter fullscreen mode Exit fullscreen mode

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

const deleteHandler = async () => {
  try {
    const response = await axios.delete(
      "https://jsonplaceholder.typicode.com/posts/1"
    )
    console.log("deleted successfully!")
  } catch (error) {
    console.log("Something went wrong", error)
  }
}
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)