Last active
December 2, 2021 14:53
-
-
Save bartwttewaall/09f04da9865876dd7c785ca97fecf9d5 to your computer and use it in GitHub Desktop.
serialize and deserialize between an object and a search string
This file contains hidden or 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
/** | |
* (de)serialize an object to a search string, like ?key=value&other=more | |
**/ | |
export function getSearchValues(key: string) { | |
const params = new URLSearchParams(location.search); | |
return params.get(key); | |
} | |
export function setSearchParams(key: string, value: any, push = false) { | |
const params = new URLSearchParams(location.search); | |
if (!!value) params.set(key, value.toString()); | |
else params.delete(key); | |
// convert params object to a string with ? delimiter or empty | |
let paramString = params.toString(); | |
paramString = !!paramString ? '?' + paramString : ''; | |
const pathname = window.location.pathname; | |
if (push === true) window.history.pushState({}, '', pathname + paramString); | |
else window.history.replaceState({}, '', pathname + paramString); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment