umami/hooks/usePageQuery.js

32 lines
720 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
export default function usePageQuery() {
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]);
function resolveUrl(params) {
2022-09-05 21:04:30 +02:00
return buildUrl(asPath.split('?')[0], { ...query, ...params });
2020-09-26 07:31:18 +02:00
}
return { pathname, query, resolveUrl, router };
2020-09-26 07:31:18 +02:00
}