catstodon/app/javascript/flavours/glitch/hooks/useSearchParam.ts
Renaud Chaput 03829d8e1d [Glitch] Update directory page options to use URL params
Port ae03e4ffc6 to glitch-soc

Signed-off-by: Claire <claire.github-309c@sitedethib.com>
2024-09-21 15:17:56 +02:00

31 lines
779 B
TypeScript

import { useMemo, useCallback } from 'react';
import { useLocation, useHistory } from 'react-router';
export function useSearchParams() {
const { search } = useLocation();
return useMemo(() => new URLSearchParams(search), [search]);
}
export function useSearchParam(name: string, defaultValue?: string) {
const searchParams = useSearchParams();
const history = useHistory();
const value = searchParams.get(name) ?? defaultValue;
const setValue = useCallback(
(value: string | null) => {
if (value === null) {
searchParams.delete(name);
} else {
searchParams.set(name, value);
}
history.push({ search: searchParams.toString() });
},
[history, name, searchParams],
);
return [value, setValue] as const;
}