set search params without the whole layout reloading

This commit is contained in:
Kalle (Sendou)
2021-01-08 15:26:08 +02:00
parent b53da05627
commit 967ce013bf
5 changed files with 27 additions and 14 deletions

18
lib/setSearchParams.ts Normal file
View File

@@ -0,0 +1,18 @@
export const setSearchParams = (key: string, value: string | undefined) => {
const url = new URL(window.location.href);
const params = new URLSearchParams(url.search);
if (!value) {
params.delete(key);
} else {
params.set(key, value); // encodeURIComponent(value)
}
history.replaceState(
{},
"",
`${window.location.pathname}${
Array.from(params.entries()).length ? "?" : ""
}${params.toString()}`
);
};