import { useCallback, useEffect, useState } from "react"; export enum Direction { ASC = 1, DESC = -1 } export function useKeySort(items: T[], key: string, direction: Direction = Direction.ASC): T[] { const predicate = useCallback((a: any, b: any) => { if (!a.hasOwnProperty(key)) return -direction; if (!b.hasOwnProperty(key)) return direction; if (a[key] > b[key]) return direction; if (a[key] < b[key]) return -direction; return 0 }, [key, direction]) return useSort(items, predicate) } export function useSort(items: T[], predicate: (a:T, b:T) => number): T[] { const [ sorted, setSorted ] = useState(items); useEffect(() => { const sorted = [ ...items ] sorted.sort(predicate) setSorted(sorted) }, [items, predicate]) return sorted }