paoloricciuti/sveltekit-search-params

Support for bind:group directive

Closed this issue · 5 comments

pejeio commented

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.

Can you provide a reproduction?

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

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?

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