svelte-autocomplete icon indicating copy to clipboard operation
svelte-autocomplete copied to clipboard

Key value pairs autocompletes to value of "key"

Open antony opened this issue 7 years ago • 6 comments

Hi - do you have the source code for http://svelte-autocomplete.surge.sh/ available anywhere?

The problem is when using key,value pairs, when I select a value, it places the "key" attribute's value into the input box.

I can't figure out why, or how to fix it.

antony avatar Sep 07 '18 15:09 antony

I've created a reproduction. I don't think the key/value pairs feature works at all.

https://svelte.technology/repl?version=2.13.4&gist=fa5a7dc64388b66da8f44c5c6cf38f34

antony avatar Sep 09 '18 19:09 antony

You have to use the component like this:

<AutoComplete 
  name="countries" 
  items="{countries}" 
  isAsync="true" 
  on:input="asyncData(event)" 
  on:change="set({ country: event })">
</AutoComplete>

and then have a method in the parent like this:

methods: {
  asyncData () {
    fetchData(apiUrl).then(data => {
      const countries = data.map(item => {
        const { name, alpha3Code } = item
        return {
          key: name,
          value: alpha3Code
        }
      })
      this.set({ countries })
    })
  }
}

elcobvg avatar Sep 10 '18 01:09 elcobvg

I've simplified your example down without asyncData (to reduce complexity)

It doesn't seem to work - and by that I mean that when you choose an item, it replaces the input text with its ID, rather than keeping the item's key:

https://svelte.technology/repl?version=2.13.4&gist=fa5a7dc64388b66da8f44c5c6cf38f34

What am I missing?

antony avatar Sep 10 '18 07:09 antony

You're forgetting to add bind:value="result", the component should be defined like this:

<AutoComplete bind:value="result" class="input" name="fruits" items="{fruits}" minChar="1" />

See https://svelte.technology/repl?version=2.13.4&gist=0c4491fc8bad2e0bd62b78e81e9c8875

elcobvg avatar Sep 10 '18 10:09 elcobvg

Ah that works - excellent.

I'd say it's a bit non-obvious though - if you look at these:

bind:value="result" on:change="set({ result: event })"

Binding an on:change shouldn't be necessary since that's what bind:value does. Additionally, setting 'result' to 'event' is very odd since 'event' is the numerical id of the item, yet 'result' as bound by the 'bind:value' statement is actually the string name.

I'll add this to the docs anyway - but I think some renaming might be useful here.

antony avatar Sep 10 '18 10:09 antony

You're absolutely right, that is strange. And I hadn't even noticed it until now... TBH, I can't quite remember why I did it that way. When I have some more time available, I'll have another look at this issue.

elcobvg avatar Sep 10 '18 10:09 elcobvg