DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Mohamad Harith
Mohamad Harith

Posted on

Mutating Query Params in SvelteKit Without Page Reloads or Navigations

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);
};
Enter fullscreen mode Exit fullscreen mode

The usage:

  onMount(() => {
    // adds ?foo=bar&john=doe query params to the URL
    replaceStateWithQuery({
      foo: 'bar',
      john: 'doe',
    });
  });
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (4)

Collapse
 
raz0229 profile image
RAZ0229

This is it. Can't believe i spend hours finding other solutions

Collapse
 
pptavozl profile image
Gustavo Zimbrรณn

Useful! Thank you!

Collapse
 
dangelomedinag profile image
dangelo

this is amazing. when you travel to the same page through a link, the client side router removes the replaced query parameters from 'onMount' and it is understandable, since the component is not mounted again. So keep that in mind.

thanks for the post.

Collapse
 
chrisjayden profile image
MultipleHats

Maybe it's me, but I think you forgot the add undefined to the Record value as well.

export const replaceStateWithQuery = (values: Record<string, string | undefined>) => {
     ....
};
Enter fullscreen mode Exit fullscreen mode

We're hiring!

We're looking for a Senior Full Stack Engineer to join the DEV team. Head here to learn more.