Home
/
Unlabelled
/
To delete a user by ID when clicking a button in a React application using Axios to interact with a REST API, follow these steps:
To delete a user by ID when clicking a button in a React application using Axios to interact with a REST API, follow these steps:
To delete a user by ID when clicking a button in a React application using Axios to interact with a REST API, follow these steps:
1. Set Up Axios
Ensure you have Axios installed in your React project:
bashnpm install axios
2. Create the Delete Function
Define a function that sends a DELETE
request to the REST API with the user's ID.
3. Implement the Button
Add a button to your component that triggers the delete function.
Example Code:
jsx
import React, { useState, useEffect } from "react";
import axios from "axios";
const UserList = () => {
const [users, setUsers] = useState([]);
// Fetch users from API
useEffect(() => {
axios.get("https://api.example.com/users")
.then((response) => {
setUsers(response.data);
})
.catch((error) => {
console.error("Error fetching users:", error);
});
}, []);
// Function to delete user by ID
const deleteUser = (id) => {
axios.delete(`https://api.example.com/users/${id}`)
.then(() => {
alert(`User with ID ${id} deleted successfully.`);
setUsers(users.filter(user => user.id !== id)); // Update the UI
})
.catch((error) => {
console.error("Error deleting user:", error);
alert("Failed to delete the user.");
});
};
return (
<div>
<h1>User List</h1>
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} - {user.email}
<button onClick={() => deleteUser(user.id)} style={{ marginLeft: "10px" }}>
Delete
</button>
</li>
))}
</ul>
</div>
);
};
export default UserList;
Key Points:
- API Endpoint: Replace
https://api.example.com/users
with the actual endpoint of your REST API. - State Update: The
setUsers
function updates the UI after a successful deletion. - Error Handling: Ensure errors are logged and the user is notified if the operation fails.
Optional: Confirm Before Deletion
You can add a confirmation dialog before deleting:
jsx
const deleteUser = (id) => {
if (window.confirm("Are you sure you want to delete this user?")) {
axios.delete(`https://api.example.com/users/${id}`)
.then(() => {
alert(`User with ID ${id} deleted successfully.`);
setUsers(users.filter(user => user.id !== id));
})
.catch((error) => {
console.error("Error deleting user:", error);
alert("Failed to delete the user.");
});
}
};
This ensures accidental deletions are avoided