diff --git a/client/src/hooks/useSort.tsx b/client/src/hooks/useSort.tsx index dad6af6..64a1102 100644 --- a/client/src/hooks/useSort.tsx +++ b/client/src/hooks/useSort.tsx @@ -5,19 +5,27 @@ export enum Direction { DESC = -1 } -export function useSort(items: T[], key: string, direction: Direction = Direction.ASC): T[] { +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((a: any, b: any) => { - if (a[key] > b[key]) return direction; - if (a[key] < b[key]) return -direction; - return 0 - }) + sorted.sort(predicate) setSorted(sorted) - }, [key, items, direction]) + }, [items, predicate]) return sorted } \ No newline at end of file diff --git a/client/src/routes/home/index.tsx b/client/src/routes/home/index.tsx index a8a9901..4cd147e 100644 --- a/client/src/routes/home/index.tsx +++ b/client/src/routes/home/index.tsx @@ -4,7 +4,7 @@ import { useHistory } from 'react-router'; import { base58UUID } from '../../util/uuid'; import { useStoredProjectList } from "../../hooks/use-stored-project-list"; import { formatDate } from "../../util/date"; -import { Direction, useSort } from "../../hooks/useSort"; +import { Direction, useKeySort, useSort } from "../../hooks/useSort"; import { useTitle } from "../../hooks/use-title"; const Home: FunctionComponent = () => { @@ -13,7 +13,7 @@ const Home: FunctionComponent = () => { const [projects] = useStoredProjectList() const [sortingKey, setSortingKey] = useState('updatedAt') const [sortingDirection, setSortingDirection] = useState(Direction.DESC) - const sortedProjects = useSort(projects, sortingKey, sortingDirection) + const sortedProjects = useKeySort(projects, sortingKey, sortingDirection) const history = useHistory() const openNewProject = () => {