Search code examples
javascriptselectbindsvelte

Pre-filled-out select in Svelte


I am currently working on a form where you can enter diverse data (text, img's and also choose pdf's).

With the latter I am having some troubles. When I want to edit a form, the Selectfield (where the pdf is safed) is empty.

First of, when I open the Modal to edit the entry, I get my data like this:

onMount(async () => {
        const data = await api.get('/documents');
        console.log({ data });

        documents = data.map((doc) => ({ value: doc.id, label: doc.name }));

        if (isEdit) {
            selectedDocument = data.find((doc) => doc.value === formInput.projectId);
        }
    });

I want to display the chosen PDF in a SelectInput field:

<div class="sm:col-span-3">
            <SelectInput
                id="files"
                items={documents}
                name="files"
                label="Dateien"
                bind:selectedItem={selectedDocument}
                class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
            />
        </div>

The component SelectInput is built like this:

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

    export let items = [];
    export let selectedItem = undefined;
    export let id;
    export let name;
    export let label;

    function handleSelect(event) {
        selectedItem = event.detail;
        console.log('selectedItem', selectedItem);
    }

    function handleClear() {
        selectedItem = undefined;
    }
</script>

<div class={`themed ${$$props.class}`}>
    <label for={id} class="block text-base font-medium text-gray-700">{label}</label>
    <Select {id} {items} {name} on:select={handleSelect} on:clear={handleClear} />
</div>

TLDR: The Select-value is not preselected like the other text-areas. Basically I want to edit a dB entry. So when I click on "edit" I want to see all the changable values (title, uppertext, lowertext, selectedItem). So far I am only able to see the textareas but not the selectable. When I open the edit, it is empty and I dont know why.


Solution

  • Because I'm not familiar with the svelte-select package, I can't be sure as to why it is not reacting to the changes. But here's what I would try to debug this:

    1. Check if there are any errors printed in the console on the server or browser?
    2. Use bind:items for <SelectInput>
    3. Use bind:items for <Select>
    4. Finally, if none of those work, you can use a key block. This will force it to re-render when the key changes.
    {#key items}
      <SelectInput
        
      />
    {/key}