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

Support for bind:group directive #70

Closed pejeio closed 6 months ago

pejeio commented 6 months ago

Describe the problem

In Svelte, you can use the bind:group feature like so:

<script lang="ts">
    let selected = []
</script>

<input type="checkbox" bind:group={selected} value="2022" />
<input type="checkbox" bind:group={selected} value="2023" />
<input type="checkbox" bind:group={selected} value="2024" />

However, when attempting to apply the same technique with the (awesome! 😎) sveltekit-search-params package, as shown:

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

    const selected = queryParam('years', ssp.array());
</script>

<input type="checkbox" bind:group={$selected} value="2022" />
<input type="checkbox" bind:group={$selected} value="2023" />
<input type="checkbox" bind:group={$selected} value="2024" />

An error occurs:

TypeError: Cannot read properties of null (reading 'indexOf')

Describe the proposed solution

It's possible that there's an error in my implementation, or perhaps this feature isn't supported yet. Regardless, having this functionality would be fantastic.

paoloricciuti commented 6 months ago

Can you provide a reproduction?

pejeio commented 6 months ago

Can you provide a reproduction?

Sure! There you go: https://codesandbox.io/p/devbox/brave-https-dvd3vk?file=%2Fsrc%2Froutes%2F%2Bpage.svelte%3A9%2C1

paoloricciuti commented 6 months ago

Ok the problem is simply that if the query param is not present the value of the store will be null. To fix this you can use the default value for the encoder/decoder

const selected = queryParam('years', ssp.array([]));
pejeio commented 6 months ago

Thanks @paoloricciuti! Much appreciated. Quick question: Whenever I do this, the ?years search parameter gets appended to the URL, even if no checkboxes are chosen. Any idea how to conceal it when no checkboxes are chosen?

paoloricciuti commented 6 months ago

Thanks @paoloricciuti! Much appreciated. Quick question: Whenever I do this, the ?years search parameter gets appended to the URL, even if no checkboxes are chosen. Any idea how to conceal it when no checkboxes are chosen?

Yes you can do set showDefaults to false

https://github.com/paoloricciuti/sveltekit-search-params?tab=readme-ov-file#showdefaults