import React, { useState, useEffect } from 'react'; import axios from 'axios'; import ConfirmBox from './ConfirmBox'; const BASE_URL = "http://localhost:8000"; const UsersTable = () => { const [users, setUsers] = useState([]); const [selectedUserId, setSelectedUserId] = useState(null); const [confirmModal, setConfirmModal] = useState(false); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [searchTerm, setSearchTerm] = useState(''); const fetchUsers = async () => { try { setLoading(true); const response = await axios.get(`${BASE_URL}/users`); const sortedUsers = response.data.data.sort((a, b) => new Date(b.created_at) - new Date(a.created_at) ); setUsers(sortedUsers); setError(null); } catch (error) { console.error("Error fetching users:", error); setError("Failed to load users. Please try again later."); } finally { setLoading(false); } }; useEffect(() => { fetchUsers(); }, []); const handleDeleteUser = async (userId) => { const token = localStorage.getItem('token'); try { await axios.delete(`${BASE_URL}/user/${userId}`, { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` } }); await fetchUsers(); setConfirmModal(false); } catch (error) { console.error("Error deleting user:", error); setError("Failed to delete user. Please try again."); } }; const filteredUsers = users.filter(user => user.username.toLowerCase().includes(searchTerm.toLowerCase()) || user.email.toLowerCase().includes(searchTerm.toLowerCase()) || user.fullName.toLowerCase().includes(searchTerm.toLowerCase()) ); if (loading) { return (
); } return (
{/* Search and filters */}
setSearchTerm(e.target.value)} />
{/* Error message */} {error && (

Error

{error}

)} {/* Table */}
{filteredUsers.map((user) => ( ))}
ID Username Email Full Name Role Created At Status Actions
{user.id} {user.username} {user.email} {user.fullName} {user.role} {new Date(user.created_at).toLocaleString("tr-TR")}
{/* Show message if no users found */} {filteredUsers.length === 0 && (
No users found matching your search criteria.
)}
{/* Confirm Delete Modal */} {confirmModal && ( handleDeleteUser(selectedUserId)} onClose={() => { setConfirmModal(false); setSelectedUserId(null); }} /> )}
); }; export default UsersTable;