umami/src/components/hooks/useNavigation.ts

33 lines
818 B
TypeScript
Raw Normal View History

2020-09-26 05:31:18 +00:00
import { useMemo } from 'react';
2023-09-29 12:29:22 +00:00
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
2022-09-05 19:04:30 +00:00
import { buildUrl } from 'next-basics';
2020-09-26 05:31:18 +00:00
2023-12-03 11:07:03 +00:00
export function useNavigation(): {
pathname: string;
query: { [key: string]: string };
router: any;
2024-01-30 08:10:25 +00:00
renderUrl: (params: any, reset?: boolean) => string;
2023-12-03 11:07:03 +00:00
} {
2020-09-26 05:31:18 +00:00
const router = useRouter();
2023-09-29 12:29:22 +00:00
const pathname = usePathname();
const params = useSearchParams();
2020-09-26 05:31:18 +00:00
const query = useMemo(() => {
2023-09-29 12:29:22 +00:00
const obj = {};
2020-09-26 05:31:18 +00:00
2023-09-29 12:29:22 +00:00
for (const [key, value] of params.entries()) {
2020-09-26 05:31:18 +00:00
obj[key] = decodeURIComponent(value);
2023-09-29 12:29:22 +00:00
}
2020-09-26 05:31:18 +00:00
2023-09-29 12:29:22 +00:00
return obj;
}, [params]);
2020-09-26 05:31:18 +00:00
2024-01-30 08:10:25 +00:00
function renderUrl(params: any, reset?: boolean) {
2023-10-03 16:45:02 +00:00
return reset ? pathname : buildUrl(pathname, { ...query, ...params });
2020-09-26 05:31:18 +00:00
}
2024-02-03 01:49:17 +00:00
return { pathname, query, router, renderUrl };
2020-09-26 05:31:18 +00:00
}
2023-05-18 06:20:06 +00:00
2023-10-03 16:45:02 +00:00
export default useNavigation;