React Axios Asynchronous HTTP DELETE Request Tutorial

In this comprehensive guide, we will show you how to make an Asynchronous HTTP DELETE request in React. To make the delete request, we will use the Axios package and a fake API.

We will make the API using the json server, and you will be given step-by-step instructions regarding the json server. Apart from that, we will also show you how to make HTTP POST and GET requests.

Axios helps you send asynchronous HTTP requests through REST endpoints and diligently handles the CRUD operations.

In React, the Axios library is used to manage HTTP requests. It is a Promise-based HTTP client for JavaScript. It is ideally used for front-end applications, including Node. Js backend.

React HTTP Asynchronous DELETE Request Example

  • Step 1: Install React App
  • Step 2: Add Axios
  • Step 3: Create Component
  • Step 3: Set Up JSON Server
  • Step 4: HTTP DELETE Request
  • Step 5: Register Component
  • Step 8: Run Application

Install React App

Go ahead and create a new React app, if the application has already been created then jump on to the subsequent step.

npx create-react-app react-http

Add Axios in React

HTTP requests can be handled with Axios, for that you must install the axios library in the react app.

npm install axios

Create Component

Now, to write the HTTP programme you need a new component. So, make the components/HttpReq.js file.

import React from 'react'

export default function AsyncPostReq() {
  return (
    <div>
      
    </div>
  )
}

Set Up JSON Server

In order to give you the demo of async HTTP request, we need API. If you don’t have real api then you may use the fake API. Below we are sharing the process of creating a fake API.

First, install the json server package with the given command.

npm i json-server

Then, create db.json file within the root of your react app.

Make sure to posts object with some data into the db.json file.

{
  "posts": [
    {
      "title": "Ronni",
      "id": 7
    },
    {
      "title": "Shia",
      "id": 8
    }
  ]
}

You can start the json server with suggested command.

json-server --watch db.json

Here is the output you will see on your terminal.

\{^_^}/ hi!

  Resources
  http://localhost:3000/posts

  Home
  http://localhost:3000

DELETE Request

All formalities have been done, now before making the delete request, we will show you how to make HTTP get, post requests.

In the below code example, we created the basic form and a list. In which user can add the data and display the data simultaneously.

The deletePost() function is being used here to make the DELETE request with JavaScript async / await.

Update components/HttpReq.js file.

import React, { useState, useEffect } from 'react'
import axios from 'axios'

export default function HttpReq() {
  const [users, initUser] = useState([])
  const [titleVal, setName] = useState('')

  const getReg = async () => {
    try {
      const res = await axios.get('http://localhost:3000/posts')
      initUser(res.data)
    } catch (e) {
      console.log(e)
    }
  }

  useEffect(() => {
    window.addEventListener('load', getReg)
    return () => {
      window.removeEventListener('load', getReg)
    }
  }, [users])

  const sumitForm = async (e) => {
    e.preventDefault()

    const post = { title: titleVal }

    try {
      const res = await axios.post('http://localhost:3000/posts/', post)
      console.log(res.data)
    } catch (e) {
      alert(e)
    }
  }

  const deletePost = async (id) => {
    try {
      const res = await axios.delete(`http://localhost:3000/posts/${id}`)
      console.log('post deleted')
    } catch (e) {
      alert(e)
    }
  }

  return (
    <div className="container mt-5">
      <form onSubmit={sumitForm}>
        <div className="mb-3">
          <input
            type="text"
            className="form-control"
            value={titleVal}
            onChange={(e) => {
              setName(e.target.value)
            }}
            placeholder="Enter title"
          />
        </div>
        <div className="d-grid">
          <button type="submit" className="btn btn-primary mb-5">
            Add
          </button>
        </div>
      </form>

      <div className="alert alert-warning text-center" role="alert">
        Results
      </div>

      <ul className="list-group">
        {users.map((res) => {
          return (
            <li
              className="list-group-item d-flex justify-content-between align-items-start"
              key={res.id}
            >
              <div className="ms-2 me-auto">
                <div className="fw-bold">{res.title}</div>
                <small className="remove" onClick={() => deletePost(res.id)}>
                  Delete
                </small>
              </div>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

Register Component

Head over to src/App.js, now import the HttpReq component and also define the component within the App() function.

import React from 'react'

import 'bootstrap/dist/css/bootstrap.min.css';
import HttpReq from './components/HttpReq'

export default function App() {
  return (
    <div>
      <HttpReq />
    </div>
  )
}

Run Application

After that, we must start the React application using the given command.

npm start

React Axios Asynchronous HTTP DELETE Request Tutorial

Summary

In this tutorial, you have learned how to make HTTP delete, post, and get requests through the Asynchronous pattern in React application. We hope this guide will help you understand HTTP requests in React more eloquently.