import React, { useState, useEffect } from 'react'; import { Table, TableHeader, TableBody, TableHead, TableRow, TableCell, TableCaption } from './ui/table'; import { Button } from './ui/button'; const DataTable = () => { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [sortConfig, setSortConfig] = useState({ key: null, direction: 'asc' }); // Mock data for demonstration - replace with actual MongoDB data const mockData = [ { id: 1, name: 'John Doe', email: 'john@example.com', role: 'Developer' }, { id: 2, name: 'Jane Smith', email: 'jane@example.com', role: 'Designer' }, { id: 3, name: 'Bob Johnson', email: 'bob@example.com', role: 'Manager' }, { id: 4, name: 'Alice Brown', email: 'alice@example.com', role: 'Developer' }, { id: 5, name: 'Charlie Wilson', email: 'charlie@example.com', role: 'Designer' }, ]; useEffect(() => { // Simulate loading data setTimeout(() => { setData(mockData); setLoading(false); }, 1000); }, []); // Sorting function const sortData = (key) => { let direction = 'asc'; // Three-state sorting: asc → desc → none if (sortConfig.key === key) { if (sortConfig.direction === 'asc') { direction = 'desc'; } else if (sortConfig.direction === 'desc') { // Reset to no sorting setSortConfig({ key: null, direction: 'none' }); return; } } setSortConfig({ key, direction }); }; // Get sorted data const getSortedData = () => { if (!sortConfig.key || sortConfig.direction === 'none') return data; return [...data].sort((a, b) => { let aValue = a[sortConfig.key]; let bValue = b[sortConfig.key]; // Handle string comparison (case-insensitive) if (typeof aValue === 'string') { aValue = aValue.toLowerCase(); bValue = bValue.toLowerCase(); } if (aValue < bValue) { return sortConfig.direction === 'asc' ? -1 : 1; } if (aValue > bValue) { return sortConfig.direction === 'asc' ? 1 : -1; } return 0; }); }; // Get sort indicator for column headers const getSortIndicator = (key) => { if (sortConfig.key !== key) return '⇵'; if (sortConfig.direction === 'asc') return '↑'; if (sortConfig.direction === 'desc') return '↓'; return '⇵'; }; const fetchFromMongoDB = async () => { try { setLoading(true); // Replace this with your actual MongoDB connection logic // const response = await fetch('/api/data'); // const result = await response.json(); // setData(result); // For now, using mock data setData(mockData); } catch (err) { setError('Failed to fetch data'); } finally { setLoading(false); } }; if (loading) { return (
Loading...
); } if (error) { return (
{error}
); } const sortedData = getSortedData(); return (

Interesting Mock Data

A list of users from the database. sortData('id')} > ID {getSortIndicator('id')} sortData('name')} > Name {getSortIndicator('name')} sortData('email')} > Email {getSortIndicator('email')} sortData('role')} > Role {getSortIndicator('role')} {sortedData.map((user) => ( {user.id} {user.name} {user.email} {user.role} ))}
); }; export default DataTable;