Skip to content

Instantly share code, notes, and snippets.

@patrinhani-ciandt
Created September 13, 2019 16:04
Show Gist options
  • Save patrinhani-ciandt/b8ebbc5b62b41ff5dd625fdb39483891 to your computer and use it in GitHub Desktop.
Save patrinhani-ciandt/b8ebbc5b62b41ff5dd625fdb39483891 to your computer and use it in GitHub Desktop.
React Hooks and Query String State sync
import qs from "query-string";
const setQueryStringWithoutPageReload = qsValue => {
const newurl =
window.location.protocol +
"//" +
window.location.host +
window.location.pathname +
qsValue;
window.history.pushState({ path: newurl }, "", newurl);
};
export const getQueryStringValue = (
key,
queryString = window.location.search
) => {
const values = qs.parse(queryString);
return values[key];
};
export const setQueryStringValue = (
key,
value,
queryString = window.location.search
) => {
const values = qs.parse(queryString);
const newQsValue = qs.stringify({
...values,
[key]: value
});
setQueryStringWithoutPageReload(`?${newQsValue}`);
};
import { useState, useCallback } from "react";
import { getQueryStringValue, setQueryStringValue } from "./queryString";
function useQueryString(key, initialValue) {
const [value, setValue] = useState(getQueryStringValue(key) || initialValue);
const onSetValue = useCallback(
newValue => {
setValue(newValue);
setQueryStringValue(key, newValue);
},
[key]
);
return [value, onSetValue];
}
export default useQueryString;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment