2023-10-08 19:35:11 +02:00
|
|
|
import { useCallback, useMemo } from "react";
|
2023-05-25 22:54:35 +02:00
|
|
|
import { useLocation } from "react-router-dom";
|
|
|
|
|
|
|
|
export function useQueryParams() {
|
|
|
|
const loc = useLocation();
|
|
|
|
|
|
|
|
const queryParams = useMemo(() => {
|
|
|
|
// Basic absolutely-not-fool-proof URL query param parser
|
2023-05-26 23:04:11 +02:00
|
|
|
const obj: Record<string, string> = Object.fromEntries(
|
|
|
|
new URLSearchParams(loc.search).entries()
|
|
|
|
);
|
2023-05-25 22:54:35 +02:00
|
|
|
|
|
|
|
return obj;
|
|
|
|
}, [loc]);
|
|
|
|
|
|
|
|
return queryParams;
|
|
|
|
}
|
2023-10-08 19:35:11 +02:00
|
|
|
|
|
|
|
export function useQueryParam(param: string) {
|
|
|
|
const params = useQueryParams();
|
|
|
|
const location = useLocation();
|
|
|
|
const currentValue = params[param];
|
|
|
|
|
|
|
|
const set = useCallback(
|
|
|
|
(value: string | null) => {
|
|
|
|
const parsed = new URLSearchParams(location.search);
|
|
|
|
if (value) parsed.set(param, value);
|
|
|
|
else parsed.delete(param);
|
|
|
|
location.search = parsed.toString();
|
|
|
|
},
|
|
|
|
[param, location]
|
|
|
|
);
|
|
|
|
|
|
|
|
return [currentValue, set] as const;
|
|
|
|
}
|