Search code examples
sveltesveltekitselectize.jsselectinput

Why is svelecte creating [object Object] when I create a new item?


In my SvelteKit project I am using the svelecte package to add selectize-style select inputs. The initial values are passed in via the the data variable created by svelte's load function when the page is requested.

<Svelecte id="category" 
    options={categories} 
    creatable = true
    on:createoption={newCategory}
    bind:value={selected}
    on:change="{do_something}">
 </Svelecte>

Within my <script> tag in the corresponding +page.svelte file I have:

let categories = data.categories;
let selected;

function newCategory(c) {
  categories.push(c.detail.value);
}

This works fine except when I try to create a new item. The new Item I create appears in the input, but then when I try to change my selection, instead of the item I created, the new option is shown as [object Object]

svelecte options after new item added

What am I doing wrong here?


Solution

  • After thinking about it some more, it occurred to me that svelecte is creating an object when I add a new item. Re-reading the docs I see that the values should be in the form of {value: value, label: label}. It through me off that just providing an array of values worked for initially creating the input. So the following change fixes it for me:

    - let categories = data.categories;
    + let categories = data.categories.map(function(c) { return({value: c, label:c}) });