Skip to content

Instantly share code, notes, and snippets.

@lukethacoder
Last active May 27, 2022 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukethacoder/4c22c35d01eb8a4127d5f2d8e3fe01dc to your computer and use it in GitHub Desktop.
Save lukethacoder/4c22c35d01eb8a4127d5f2d8e3fe01dc to your computer and use it in GitHub Desktop.
get the url params object from a search string (url string || window.location.search)
/**
* Retrieve URL params from the url
*/
export const getUrlParams = (search = window.location.search) => {
return [...new URLSearchParams(search).entries()].reduce(
(acc, [key, value]) => {
const _value = decodeURIComponent(value)
return {
...acc,
[key]: _value !== 'null' && _value !== 'undefined' ? _value : undefined,
}
},
{}
)
}
/**
* @param {Object} object Object of key/values to set as URL params
* @param {String}[window.location.pathname] basePath - base path to append the url params to
*/
export const setUrlParams = (
object,
{
existingSearch = window.location.search,
shouldPush = true,
basePath = window.location.pathname,
}
) => {
const params = new URLSearchParams(existingSearch)
Object.keys(object).forEach((key) => {
if (object[key] !== undefined) {
params.set(key, encodeURIComponent(object[key]))
}
})
const newUrl = `${basePath}?${params.toString()}`
// only update the state if it has actually changed
if (
`${window.location.pathname}/${existingSearch}` !== newUrl &&
`${window.location.pathname}${existingSearch}` !== newUrl
) {
// creates a new history entry
if (shouldPush) {
window.history.pushState({ path: newUrl }, '', newUrl)
} else {
// replaces the current history entry
window.history.replaceState({ path: newUrl }, '', newUrl)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment