umami/src/components/hooks/usePageQuery.js

28 lines
657 B
JavaScript
Raw Normal View History

2020-09-26 07:31:18 +02:00
import { useMemo } from 'react';
2023-09-29 14:29:22 +02:00
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
2022-09-05 21:04:30 +02:00
import { buildUrl } from 'next-basics';
2020-09-26 07:31:18 +02:00
2023-05-18 08:20:06 +02:00
export function usePageQuery() {
2020-09-26 07:31:18 +02:00
const router = useRouter();
2023-09-29 14:29:22 +02:00
const pathname = usePathname();
const params = useSearchParams();
2020-09-26 07:31:18 +02:00
const query = useMemo(() => {
2023-09-29 14:29:22 +02:00
const obj = {};
2020-09-26 07:31:18 +02:00
2023-09-29 14:29:22 +02:00
for (const [key, value] of params.entries()) {
2020-09-26 07:31:18 +02:00
obj[key] = decodeURIComponent(value);
2023-09-29 14:29:22 +02:00
}
2020-09-26 07:31:18 +02:00
2023-09-29 14:29:22 +02:00
return obj;
}, [params]);
2020-09-26 07:31:18 +02:00
2023-04-02 06:06:11 +02:00
function resolveUrl(params, reset) {
2023-09-29 14:29:22 +02:00
return buildUrl(pathname, { ...(reset ? {} : query) });
2020-09-26 07:31:18 +02:00
}
return { pathname, query, resolveUrl, router };
2020-09-26 07:31:18 +02:00
}
2023-05-18 08:20:06 +02:00
export default usePageQuery;