1
0
Fork 0
mirror of https://github.com/sussy-code/smov.git synced 2025-01-01 16:37:39 +01:00
smov/src/hooks/useQueryParams.ts
2023-12-23 18:24:43 +13:00

39 lines
978 B
TypeScript

import { useCallback, useMemo } from "react";
import { useLocation, useNavigate } from "react-router-dom";
export function useQueryParams() {
const loc = useLocation();
const queryParams = useMemo(() => {
const obj: Record<string, string> = Object.fromEntries(
new URLSearchParams(loc.search).entries(),
);
return obj;
}, [loc.search]);
return queryParams;
}
export function useQueryParam(
param: string,
): [string | null, (a: string | null) => void] {
const params = useQueryParams();
const location = useLocation();
const navigate = useNavigate();
const currentValue = params[param] ?? null;
const set = useCallback(
(value: string | null) => {
const parsed = new URLSearchParams(location.search);
if (value) parsed.set(param, value);
else parsed.delete(param);
navigate({
search: parsed.toString(),
});
},
[param, location.search, navigate],
);
return [currentValue, set];
}