Open
Description
import { useHistory, useLocation } from "react-router-dom";
export const useSearchParams = (): UseSearchParams => {
const history = useHistory();
const location = useLocation<Record<string, string>>();
const params = new URLSearchParams(location.search);
const getParam = (paramName: string) => params.get(paramName);
const updateParams = (newParams: Record<string, string>): URLSearchParams => {
Object.entries(newParams).forEach(([newKey, newValue]) => {
if (params.has(newKey)) {
params.delete(newKey);
}
params.set(newKey, newValue);
});
params.sort();
return params;
};
const goToUpdatedParams = (newParams: Record<string, string>) => {
history.replace({
...location,
search: updateParams(newParams).toString(),
});
};
const clearParam = (paramToDelete: string) => {
if (params.has(paramToDelete)) {
params.delete(paramToDelete);
}
history.replace({
...location,
search: params.toString(),
});
};
return {
getParam,
updateParams,
clearParam,
};
};
interface UseSearchParams {
updateParams: (params: Record<string, string>) => void;
getParam: (key: string) => string | null;
clearParam: (key: string) => void;
}
Metadata
Metadata
Assignees
Labels
No labels