How to timeout fetch requests in JavaScript

How to timeout fetch requests in JavaScript

Written by collegewap on Aug 12th, 2022 Views Report Post

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

Now install axios using the following command:

npm i axios

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

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

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!")
}

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!")
    })
}

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)
    })
}

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)
  }
}

Comments (0)