forked from Vero-protocol/vero-guardian-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseTaskFilters.ts
More file actions
53 lines (43 loc) · 1.47 KB
/
Copy pathuseTaskFilters.ts
File metadata and controls
53 lines (43 loc) · 1.47 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
41
42
43
44
45
46
47
48
49
50
51
52
53
'use client';
import { useCallback, useMemo } from 'react';
import { useSearchParams, useRouter, usePathname } from 'next/navigation';
export interface TaskFiltersState {
status: string;
priority: string;
}
const DEFAULT_FILTERS: TaskFiltersState = {
status: 'all',
priority: 'all',
};
function parseFilters(sp: URLSearchParams): TaskFiltersState {
const status = sp.get('status') || DEFAULT_FILTERS.status;
const priority = sp.get('priority') || DEFAULT_FILTERS.priority;
return { status, priority };
}
export function useTaskFilters() {
const searchParams = useSearchParams();
const router = useRouter();
const pathname = usePathname();
const filters = useMemo(() => parseFilters(searchParams), [searchParams]);
const setFilter = useCallback(
(key: keyof TaskFiltersState, value: string) => {
const next = new URLSearchParams(searchParams.toString());
if (value === DEFAULT_FILTERS[key]) {
next.delete(key);
} else {
next.set(key, value);
}
const qs = next.toString();
router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
},
[searchParams, router, pathname],
);
const resetFilters = useCallback(() => {
router.replace(pathname, { scroll: false });
}, [router, pathname]);
const activeCount = useMemo(
() => [filters.status !== 'all', filters.priority !== 'all'].filter(Boolean).length,
[filters],
);
return { filters, setFilter, resetFilters, activeCount };
}