This content originally appeared on DEV Community and was authored by Mohamad Harith
This article assumes the reader understands the basics of SvelteKit framework.
SvelteKit is a rather new framework for building server-side rendered websites. Because it is new, some of the early adopters of the framework were confused on certain usages of the framework. One such confusion was on the usage of query params as seen in these issues: #2785, #969, #2811 - many people, including myself were confused on how to mutate query params of a page without page reloads or navigations.
Some of us thought mutating the params property of $page store would mutate the query params. But this wasn't the cause because the $page store was a read-only store.
Since SvelteKit does not provide a way to mutate the query params, my HOD and I figured that we use the History API's replace state to mutate the query params.
The function:
export const replaceStateWithQuery = (values: Record<string, string>) => {
const url = new URL(window.location.toString());
for (let [k, v] of Object.entries(values)) {
if (!!v) {
url.searchParams.set(encodeURIComponent(k), encodeURIComponent(v));
} else {
url.searchParams.delete(k);
}
}
history.replaceState({}, '', url);
};
The usage:
onMount(() => {
// adds ?foo=bar&john=doe query params to the URL
replaceStateWithQuery({
foo: 'bar',
john: 'doe',
});
});
The replaceStateWithQuery is a function that receives an object of query params and uses the History API's to set these values as the query params of the page. Both the keys and values of the query params will be URL encoded by default. If the value of a query param is null
or undefined
, the query will be deleted from the URL.
This content originally appeared on DEV Community and was authored by Mohamad Harith
Mohamad Harith | Sciencx (2021-12-24T13:19:04+00:00) Mutating Query Params in SvelteKit Without Page Reloads or Navigations. Retrieved from https://www.scien.cx/2021/12/24/mutating-query-params-in-sveltekit-without-page-reloads-or-navigations/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.