fix: correctly handle missing property in useKeySort
This commit is contained in:
parent
980f37c4eb
commit
1c2b0bb9d9
|
@ -5,19 +5,27 @@ export enum Direction {
|
|||
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);
|
||||
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
|
||||
}
|
|
@ -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>(Direction.DESC)
|
||||
const sortedProjects = useSort(projects, sortingKey, sortingDirection)
|
||||
const sortedProjects = useKeySort(projects, sortingKey, sortingDirection)
|
||||
const history = useHistory()
|
||||
|
||||
const openNewProject = () => {
|
||||
|
|
Loading…
Reference in New Issue