forked from microsoft/Solution-Accelerators
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSortDeepLink.ts
More file actions
40 lines (34 loc) · 1.13 KB
/
Copy pathuseSortDeepLink.ts
File metadata and controls
40 lines (34 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { useState, useEffect, useCallback } from 'react';
import { getSortFromUrl, updateUrlWithSort, isValidSortParam } from '../utils/sortDeepLink';
export const useSortDeepLink = (defaultSort: string = "releaseNewest") => {
const [sortBy, setSortBy] = useState<string>(() => {
const urlSort = getSortFromUrl();
return isValidSortParam(urlSort) ? urlSort : defaultSort;
});
const updateSort = useCallback((newSort: string) => {
if (isValidSortParam(newSort) && newSort !== sortBy) {
setSortBy(newSort);
updateUrlWithSort(newSort);
}
}, [sortBy]);
useEffect(() => {
const handlePopState = () => {
const urlSort = getSortFromUrl();
if (isValidSortParam(urlSort) && urlSort !== sortBy) {
setSortBy(urlSort);
}
};
window.addEventListener('popstate', handlePopState);
return () => window.removeEventListener('popstate', handlePopState);
}, [sortBy]);
useEffect(() => {
const urlSort = getSortFromUrl();
if (isValidSortParam(urlSort) && urlSort !== sortBy) {
updateUrlWithSort(sortBy);
}
}, [sortBy]);
return {
sortBy,
updateSort,
};
};