Search code examples
sveltesvelte-3svelte-componentsvelte-store

Svelte two way Store Binding in wrong order


The value of a Svelte store is overwritten with 'null' by the bound Select component from Svelte-Select Library.

Writable store: const export store = writable("startingValue")
Component with binding: <Select bind:justValue={$store} />

Since the component's justValue property is readonly, it's not possible to set it.

What's the simplest way to have an initially selected item using the store starting value (like the HTML option selected attribute)?


Solution

  • Use value instead of justValue and set it to the item you want to be selected

    REPL

    <script>    
        import Select from 'svelte-select';
        import {writable} from 'svelte/store'
    
        let items = ["value1", "value2", "value3"];
    
        const value = writable(items[0])
    </script>
    
    <Select {items} bind:value={$value}/>
    

    (inside the component you wouldn't need a store)

    items can either be an array of strings or objects in the form (group/selectable optional)

    {value: 'cake', label: 'Cake', group: 'Sweet', selectable: false}
    

    In case of strings, these seem to be converted to the object form behind the scenes (see logs in REPL) and justValue is so always holding item.value of the selected item