umami/hooks/usePageQuery.js

34 lines
764 B
JavaScript
Raw Normal View History

2020-09-26 07:31:18 +02:00
import { useMemo } from 'react';
import { useRouter } from 'next/router';
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();
const { pathname, search } = location;
2022-09-05 21:04:30 +02:00
const { asPath } = router;
2020-09-26 07:31:18 +02:00
const query = useMemo(() => {
if (!search) {
return {};
}
const params = search.substring(1).split('&');
return params.reduce((obj, item) => {
const [key, value] = item.split('=');
obj[key] = decodeURIComponent(value);
return obj;
}, {});
}, [search]);
2023-04-02 06:06:11 +02:00
function resolveUrl(params, reset) {
return buildUrl(asPath.split('?')[0], { ...(reset ? {} : query), ...params });
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;