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

40 lines
965 B
TypeScript
Raw Normal View History

import { useCallback, useMemo } from "react";
import { useHistory, useLocation } from "react-router-dom";
export function useQueryParams() {
const loc = useLocation();
const queryParams = useMemo(() => {
2023-05-26 23:04:11 +02:00
const obj: Record<string, string> = Object.fromEntries(
new URLSearchParams(loc.search).entries()
);
return obj;
2023-10-13 21:41:44 +02:00
}, [loc.search]);
return queryParams;
}
2023-10-09 21:00:58 +02:00
export function useQueryParam(
param: string
): [string | null, (a: string | null) => void] {
const params = useQueryParams();
const location = useLocation();
const router = useHistory();
2023-10-09 21:00:58 +02:00
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);
router.push({
search: parsed.toString(),
});
},
[param, location, router]
);
2023-10-09 21:00:58 +02:00
return [currentValue, set];
}