fix: correctly handle missing property in useKeySort

This commit is contained in:
wpetit 2023-09-01 20:02:36 -06:00
parent 980f37c4eb
commit 1c2b0bb9d9
2 changed files with 17 additions and 9 deletions

View File

@ -5,19 +5,27 @@ export enum Direction {
DESC = -1 DESC = -1
} }
export function useSort<T>(items: T[], key: string, direction: Direction = Direction.ASC): T[] { export function useKeySort<T>(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<T>(items: T[], predicate: (a:T, b:T) => number): T[] {
const [ sorted, setSorted ] = useState(items); const [ sorted, setSorted ] = useState(items);
useEffect(() => { useEffect(() => {
const sorted = [ ...items ] const sorted = [ ...items ]
sorted.sort((a: any, b: any) => { sorted.sort(predicate)
if (a[key] > b[key]) return direction;
if (a[key] < b[key]) return -direction;
return 0
})
setSorted(sorted) setSorted(sorted)
}, [key, items, direction]) }, [items, predicate])
return sorted return sorted
} }

View File

@ -4,7 +4,7 @@ import { useHistory } from 'react-router';
import { base58UUID } from '../../util/uuid'; import { base58UUID } from '../../util/uuid';
import { useStoredProjectList } from "../../hooks/use-stored-project-list"; import { useStoredProjectList } from "../../hooks/use-stored-project-list";
import { formatDate } from "../../util/date"; import { formatDate } from "../../util/date";
import { Direction, useSort } from "../../hooks/useSort"; import { Direction, useKeySort, useSort } from "../../hooks/useSort";
import { useTitle } from "../../hooks/use-title"; import { useTitle } from "../../hooks/use-title";
const Home: FunctionComponent = () => { const Home: FunctionComponent = () => {
@ -13,7 +13,7 @@ const Home: FunctionComponent = () => {
const [projects] = useStoredProjectList() const [projects] = useStoredProjectList()
const [sortingKey, setSortingKey] = useState('updatedAt') const [sortingKey, setSortingKey] = useState('updatedAt')
const [sortingDirection, setSortingDirection] = useState<Direction>(Direction.DESC) const [sortingDirection, setSortingDirection] = useState<Direction>(Direction.DESC)
const sortedProjects = useSort(projects, sortingKey, sortingDirection) const sortedProjects = useKeySort(projects, sortingKey, sortingDirection)
const history = useHistory() const history = useHistory()
const openNewProject = () => { const openNewProject = () => {