paoloricciuti / sveltekit-search-params

The easiest way to read and WRITE from query parameters in sveltekit.
https://sveltekit-search-params.netlify.app
MIT License
478 stars 13 forks source link

Remove the query string from the URL when a parameter isn't set #77

Closed mikenikles closed 5 months ago

mikenikles commented 5 months ago

Describe the problem

I have a search query string parameter bound to a search input field. Ideally, when the search input field is empty, I'd like to see the search query string disappear from the URL. Currently, it shows ?search=.

Describe the proposed solution

The current solution is this:

function nullableQueryParam<T>({
  encode,
  ...codec
}: EncodeAndDecodeOptions<T>) {
  return {
    ...codec,
    encode(value) {
      if (value === "") return undefined;
      if (Array.isArray(value) && value.length === 0) return undefined;

      return encode(value);
    },
  } as EncodeAndDecodeOptions<T>;
}

Then use it as follows:

export function getUrlSearchParamsFiltersStore() {
  return queryParam<string[]>("filters", nullableQueryParam(ssp.array()));
}
paoloricciuti commented 5 months ago

The problem I see with this is that technically when the search param is not there the value is null. In some occasions having it disappear would be good in other would be bad.

However there is a better solution: you can use the default of '' and set showDefaults to false

<script lang="ts">
    import { queryParam, ssp } from 'sveltekit-search-params';

    const search = queryParam('search', ssp.string(''), {
        showDefaults: false,
    });
</script>

EDIT: string, not number lol

mikenikles commented 5 months ago

Oh, very elegant. I missed that in the release notes 😊.