Created
September 13, 2019 16:04
-
-
Save patrinhani-ciandt/b8ebbc5b62b41ff5dd625fdb39483891 to your computer and use it in GitHub Desktop.
React Hooks and Query String State sync
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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