import { useState, useMemo } from 'react'; export const useSortableData = (items, config = null) => { const [sortConfig, setSortConfig] = useState(config); const sortedItems = useMemo(() => { let sortableItems = [...items]; if (sortConfig !== null) { sortableItems.sort((a, b) => { const aValue = sortConfig.key(a).toLowerCase(); const bValue = sortConfig.key(b).toLowerCase(); if (aValue < bValue) return sortConfig.direction === 'asc' ? -1 : 1; if (aValue > bValue) return sortConfig.direction === 'asc' ? 1 : -1; return 0; }); } return sortableItems; }, [items, sortConfig]); const requestSort = (keyFn) => { let direction = 'asc'; if ( sortConfig && sortConfig.key.toString() === keyFn.toString() && sortConfig.direction === 'asc' ) { direction = 'desc'; } setSortConfig({ key: keyFn, direction }); }; return { items: sortedItems, requestSort, sortConfig }; };