@scaleway/use-query-params
Version:
A small hook to handle params
61 lines (60 loc) • 1.72 kB
JavaScript
import queryString from "query-string";
import { useMemo, useCallback } from "react";
import { useNavigate, useLocation } from "react-router-dom";
const { parse } = queryString;
const { stringify } = queryString;
const useQueryParams = () => {
const navigate = useNavigate();
const location = useLocation();
const currentState = useMemo(
() => queryString.parse(location.search, {
arrayFormat: "comma",
parseBooleans: true,
parseNumbers: true
}),
[location.search]
);
const stringyFormat = useCallback(
(params) => queryString.stringify(params, {
arrayFormat: "comma",
skipEmptyString: true,
skipNull: true,
sort: (a, b) => a.localeCompare(b)
}),
[]
);
const replaceInUrlIfNeeded = useCallback(
(newState, options) => {
const stringifiedParams = stringyFormat(newState);
const searchToCompare = location.search || "?";
if (searchToCompare !== `?${stringifiedParams}`) {
navigate(`${location.pathname}?${stringifiedParams}`, {
replace: !options?.push
});
}
},
[navigate, location.pathname, location.search, stringyFormat]
);
const setQueryParams = useCallback(
(nextParams, options) => {
replaceInUrlIfNeeded({ ...currentState, ...nextParams }, options);
},
[currentState, replaceInUrlIfNeeded]
);
const replaceQueryParams = useCallback(
(newParams, options) => {
replaceInUrlIfNeeded(newParams, options);
},
[replaceInUrlIfNeeded]
);
return {
queryParams: currentState,
replaceQueryParams,
setQueryParams
};
};
export {
useQueryParams as default,
parse as parseQueryParams,
stringify as stringifyQueryParams
};