Last active
June 30, 2021 19:23
-
-
Save matiaslopezd/c8481e1e94d96f95949a6f6e15abc2ed to your computer and use it in GitHub Desktop.
Set and get search params without reload
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
function getSearchParams() { | |
const { search } = window.location; | |
const params = new URLSearchParams(search); | |
const query = {}; | |
params.forEach((value, key) => { | |
query[key] = value; | |
}); | |
return query; | |
} |
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
function setSearchParams(newParams = {}, override = false) { | |
const { search, protocol, host, pathname } = window.location; | |
const current = override ? {} : search; | |
const params = new URLSearchParams(current); | |
const keys = Object.keys(newParams); | |
keys.forEach(param => params.set(param, newParams[param])); | |
const title = window.title; | |
const url = `${protocol}//${host}${pathname}?${params.toString()}`; | |
window.history.pushState({ path: url }, title, url); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment