(data: T[], initialSortBy = "", initialDirection: SortDirection = "asc", comparators?: Comparators<T>)
| 19 | |
| 20 | // Encapsulates the sortBy/sortDirection/useMemo pattern pages hand-roll around SortableTableHead. |
| 21 | export const useSortableData = <T, >(data: T[], initialSortBy = "", initialDirection: SortDirection = "asc", comparators?: Comparators<T>): UseSortableDataResult<T> => { |
| 22 | const [sortBy, setSortBy] = useState(initialSortBy); |
| 23 | const [sortDirection, setSortDirection] = useState<SortDirection>(initialDirection); |
| 24 | |
| 25 | const handleSort = (key: string) => { |
| 26 | setSortDirection(sortBy === key && sortDirection === "asc" ? "desc" : "asc"); |
| 27 | setSortBy(key); |
| 28 | }; |
| 29 | |
| 30 | const sorted = useMemo(() => { |
| 31 | if (!sortBy) return data; |
| 32 | const custom = comparators?.[sortBy]; |
| 33 | const dir = sortDirection === "asc" ? 1 : -1; |
| 34 | return [...data].sort((a, b) => (custom ? custom(a, b) : defaultCompare((a as Record<string, unknown>)[sortBy], (b as Record<string, unknown>)[sortBy])) * dir); |
| 35 | }, [data, sortBy, sortDirection, comparators]); |
| 36 | |
| 37 | return { sorted, sortBy, sortDirection, handleSort }; |
| 38 | }; |
no test coverage detected