rob-balfre / svelte-select

Svelte Select. A select component for Svelte
https://svelte-select-examples.vercel.app
Other
1.25k stars 175 forks source link

How can I bind:value while the value key is not named 'value' #664

Closed kodaicoder closed 3 months ago

kodaicoder commented 5 months ago

I have a collection like

const colllection = 
[
     { id:1,  name:"John Doe"},
     { id:2 , name:"Jane Doe"},
     { id:3 , name:"Richard Roe"},
     { id:4 , name:"Rachel Roe"}
]

then in data from sever-side I has passing a object name initialUserId and using in svelte file like this

<script>
    import Select from 'svelte-select';

    /** @type {import('./$types').PageData} */
    export let data;

     const colllection = 
     [
          { id:1,  name:"John Doe"},
          { id:2 , name:"Jane Doe"},
          { id:3 , name:"Richard Roe"},
          { id:4 , name:"Rachel Roe"}
     ]
</script>
<Select
    placeholder="Choose user"                               
    itemId="id"
    label="name"
    items={colllection }
bind:value={data.initialUserId}
/>

but this will giving me a undefined in svelte-select box any suggestion on this issue or I using bind:value incorrectly

here is a demo

devxalted commented 5 months ago

IMO it's broken, instead of displaying undefined it should be showing the placeholder text.. but perhaps I don't fully understand how it works either.

For now, I was able to extract the value of the select by removing the bind:value attribute and creating an on:change handler and accessing the detail property of the event. By removing the data binding it allows your placeholder to display.

Demo

Hope this helps.

jamesscottbrown commented 5 months ago

The value of the value prop corresponds to an entry in the collection array, not just the id of an entry (which could be accessed as justValue but is read-only).

Try something like:

let value = colllection.find(user => user.id === data.currentUserId);

And:

<Select
   placeholder="Choose user"    
   itemId="id"
   label="name"
   items={colllection}
    bind:value
/>

And then either respond to changes in value or listen to the on:change event on the Select component to handle changes in the selection appropriately.

rob-balfre commented 3 months ago
<script>
    import Select from 'svelte-select';
    export let data;
        const collection = 
    [
         { id:1,  name:"John Doe"},
         { id:2 , name:"Jane Doe"},
         { id:3 , name:"Richard Roe"},
         { id:4 , name:"Rachel Roe"}
    ];

    let value = collection.find(c => c.id === data.initialUserId);
</script>

<Select
   placeholder="Choose user"    
   itemId="id"
   label="name"
   items={collection}
   bind:value
/>