If you are a React developer, then you must know how to delete a resource on the server?
Well, do not worry; if you are new to React, In this step by step tutorial, we will profoundly explain how to make asynchronous HTTP delete request in React js app.
In computer science, Asynchronous means that what doesn’t happen at the same time. It is a new technique that helps process a single HTTP request using a non-blocking I/O.
Theoretically, the main reason for using Asynchronous HTTP is that; when the client is interviewing the server for awaited response.
HTTP Delete request an ideally used to remove or delete a resource or data object from the server.
To create a consensus with the remote server, we use HTTP methods. To utterly establish the communication with the server, we will use the Axios package.
Axios package is a JavaScript client-side library that allows you to make an HTTP request. We will use Axios to send the HTTP delete request to remove the single data object using the object id in React application.
We expect you have installed the React application, however if not.
To install the new React application, you must open the terminal app or you might use the code editor’s integrated terminal.
There after type the following command on the terminal and run the command to form the new app.
npx create-react-app react-blog
Further, enter into the app by using given command.
cd react-blog
We are also using the demo json server, allowing us to create a demo REST API. On your terminal, type and run the suggested command.
JSON Server is a notable Node module that you can use to build demo REST JSON services effortlessly and quickly.
npm install json-server
To create the fake REST API, you will only need a JSON file, and you will have to add some sample data into it.
Hence, create a new db.json file in your react project. Also, insert some data into the file as shown below.
{
"users": [
{
"id": 1,
"name": "Anthony"
},
{
"id": 2,
"name": "Bruce"
},
{
"id": 3,
"name": "Ronni"
}
]
}
Here is the command that needs to be run through terminal.
json-server --watch db.json --port=5555
Now, you can check the data on given APIs.
Resources
http://localhost:5555/users
Home
http://localhost:5555
Now, head over to terminal and again type a new command this command will help you install the axios client in React app.
npm install axios
In this section, we will show you how to use React hooks in functional component, make HTTP Post, Get and most importantly delete request.
Get ready to create components/ folder in your project.
Immediately after, create a Users.js file in components folder.
Now, we are ready to import the required module and code into the user component file.
import React, { useState, useEffect } from 'react'
import axios from 'axios'
export default function Users() {
const [items, setItem] = useState([])
const [naveProp, initNameProp] = useState('')
const URI = 'http://localhost:5555/users'
const sendRequest = async () => {
try {
const res = await axios.get(URI)
setItem(res.data)
} catch (e) {
console.log(e)
}
}
useEffect(() => {
window.addEventListener('load', sendRequest)
return () => {
window.removeEventListener('load', sendRequest)
}
}, [items])
const onFormSubmit = async (e) => {
e.preventDefault()
const post = { name: naveProp }
try {
const res = await axios.post(URI, post)
console.log(res.data)
} catch (e) {
alert(e)
}
}
const removeUser = async (id) => {
try {
const res = await axios.delete(`${URI}/${id}`)
console.log('Item successfully deleted.')
} catch (error) {
alert(error)
}
}
return (
<div>
<form onSubmit={onFormSubmit}>
<div className="mb-3">
<input
type="text"
className="form-control"
value={naveProp}
placeholder="Add name"
onChange={(e) => {
initNameProp(e.target.value)
}}
/>
</div>
<button type="submit" className="btn btn-dark mt-3 mb-4">
Create
</button>
</form>
<ul className="list-group">
{items.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.name}</div>
<small className="remove" onClick={() => removeUser(res.id)}>
Delete
</small>
</div>
</li>
)
})}
</ul>
</div>
)
}
Now, to test the app, we need to update the component into the App.js file.
import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css';
import Users from './components/Users'
export default function App() {
return (
<div className="container mt-3">
<Users />
</div>
)
}
Now, we are ready to view the app in the browser. We can now check out how to remove or delete data with an HTTP delete request in React.
Use the following command to start the react application server.
npm start
In this eloquent yet straightforward React Axios Delete Request example, we revealed the process bit by bit. We learned to use Axios with React; we described everything through simple steps in this definitive guide.
I hope you loved our holistic approach to simplifying the fundamentals of the Axios delete method. Furthermore, you can also delete multiple items using Axios in React.
In this post, we will learn how to work with HTTP requests in the Redux…
MySQL is a relational database management system based on SQL – Structured Query Language, and…
React Js Handle Rest API data globally with Context and useState hook tutorial. In this…
Node js delete data from MySQL database tutorial; Throughout this guide, you will ascertain how…
In this tutorial, you will discover how to import CSV file into MySQL database using…
React Js Global state management with createContext hook example; In this tutorial, we will help…