http-response-handler
Version:
A comprehensive utility for standardizing HTTP responses in Node.js applications
85 lines (68 loc) • 2.4 kB
JSX
import { useState, useEffect } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
function UserGet() {
const [users, setUsers] = useState([]);
const token = localStorage.getItem("token");
const Navigate = useNavigate();
useEffect(() => {
fetchUsers();
},[]);
const fetchUsers = async () => {
try {
const response = await axios.get(
"http://localhost:5500/user/getall",
{
headers: { Authorization: `Bearer ${token}` },
}
);
setUsers(response.data.users);
} catch (error) {
toast.error("Failed to fetch users");
}
};
const handleDelete = async (id) => {
try {
const response = await axios.delete(
`http://localhost:5500/user/delete/${id}`,
{
headers: { Authorization: `Bearer ${token}` },
},
);
setMessage(response.data.message);
} catch (error) {
setMessage(error.response.data.message);
}
};
return (
<>
<h1>User List</h1>
<table border="1" width="100%" style={{ textAlign: "center" }}>
<thead>
<tr>
<th>Username</th>
<th>Email</th>
<th>Role</th>
<th>Password</th>
<th>Mobile</th>
<th>Action</th>
</tr>
</thead>
{users.map((user) => (
<tr>
<td>{user.username}</td>
<td>{user.email}</td>
<td>{user.role}</td>
<td>{user.password}</td>
<td>{user.mobile}</td>
<td>
<button onClick={() => Navigate(`/user/update/${user._id}`)}>Edit</button>
<button onClick={() => handleDelete(user._id)}>Delete</button>
</td>
</tr>
))}
</table>
</>
)
}
export default UserGet;