Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import qs from "qs";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "../routing";
const identity = a => a;
const defined = a => typeof a !== "undefined";
const fromQueryString = query => qs.parse(query, { ignoreQueryPrefix: true });
const toQueryString = object => qs.stringify(object, { addQueryPrefix: true });
export default function useQueryParam(
paramName,
defaultValue,
{ validator = defined, serializer = identity, deserializer = identity } = {},
) {
const {
location: { search },
history,
} = useRouter();
const queryParameters = useMemo(() => fromQueryString(search), [search]);
const queryParameterValue = deserializer(queryParameters[paramName]);
const [value, setValue] = useState(
validator(queryParameterValue) ? queryParameterValue : defaultValue,
);
const sValue = useMemo(() => serializer(value), [serializer, value]);
const nextSearch = useMemo(
() =>
toQueryString({
...queryParameters,
[paramName]: sValue === serializer(defaultValue) ? undefined : sValue,
}),
[defaultValue, paramName, queryParameters, sValue, serializer],
);
useEffect(() => {
if (nextSearch !== search) history.replace({ search: nextSearch });
}, [history, nextSearch, search]);
return [value, setValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment