Svelte binded select value is not updating on fetch

Viewed 1422

I'm using the following code in Svelte (3) to fetch options from an API. There's subsequent s that depend on the first one. My expectation is that selectedOption would change to options[0] when the select has its options populated but it's not changing until I manually select another option and then select the first one. Am I binding it wrong? AFAIK I don't need a reactive variable for this and should theoretically work like this.

onmount(async () => {
    options = await getOptions()
})
let selectedOption;

<select bind:value={selectedOption}>
{#each options as option}
    <option value={option} selected={selectedOption === option}>
        {option.name}
    </option>
{/each}
2 Answers

Using bind:value on a select only updates the bound variable when a change event fires. Since populating the options does not fire a change event, selectedOption won't be updated until you select an option.

I would suggest not rendering the <select> until options are completely populated. This will make sure selectedOption is set immediately.

{#if options.length > 0}
    <select bind:value={selectedOption} >
        {#each options as option}
                <option value={option} selected={selectedOption === option}>
                        {option.name}
                </option>
        {/each}
    </select>
{/if}

Maybe if you instantiate selectedOption after getOptions() function is finished executing. And you should also make selected be the 0 index option.

let selectedOption;

onmount(async () => {
    options = await getOptions()
    selectedOption = options[0]
})

<select bind:value={selectedOption}>
{#each options as option}
    <option value={option} selected={option.id == 0}>
        {option.name}
    </option>
{/each}
Related