MCPcopy Create free account
hub / github.com/dailydotdev/apps / useQueryTab

Function useQueryTab

packages/shared/src/components/shell/useQueryTab.ts:23–74  ·  view source on GitHub ↗
(
  tabs: readonly T[],
  { isAddressed = true }: { isAddressed?: boolean } = {},
)

Source from the content-addressed store, hash-verified

21// but open on the tab a link names.
22// `isAddressed` is off where a route change would trip an exit prompt.
23export const useQueryTab = <T extends string>(
24 tabs: readonly T[],
25 { isAddressed = true }: { isAddressed?: boolean } = {},
26): QueryTab<T> => {
27 const router = useRouter();
28 const isPhone = useIsPhone();
29 const [localTab, setLocalTab] = useState<T>();
30 const fromQuery = isPhone && isAddressed;
31 const queryTab = router?.query?.[tabParam];
32 const addressedTab = isAddressed
33 ? tabs.find((tab) => toSlug(tab) === queryTab)
34 : undefined;
35 const activeTab = fromQuery
36 ? (addressedTab ?? tabs[0])
37 : (localTab ?? addressedTab ?? tabs[0]);
38
39 const setActiveTab = useCallback(
40 (tab: T) => {
41 if (!fromQuery) {
42 setLocalTab(tab);
43 return;
44 }
45
46 const [path, search = ''] = router.asPath.split('#')[0].split('?');
47 const params = new URLSearchParams(search);
48
49 if (tab === tabs[0]) {
50 params.delete(tabParam);
51 } else {
52 params.set(tabParam, toSlug(tab));
53 }
54
55 const query = params.toString();
56 router.replace(query ? `${path}?${query}` : path, undefined, {
57 shallow: true,
58 scroll: false,
59 });
60 },
61 [fromQuery, router, tabs],
62 );
63
64 const segments = tabs.map((tab) => ({
65 key: tab,
66 label: tab,
67 active: tab === activeTab,
68 onClick: () => setActiveTab(tab),
69 }));
70
71 const isTabKnown = !isAddressed || router?.isReady !== false;
72
73 return { activeTab, isTabKnown, setActiveTab, segments };
74};

Calls 4

useIsPhoneFunction · 0.90
toSlugFunction · 0.85
replaceMethod · 0.80
useRouterFunction · 0.50

Tested by

no test coverage detected