Skip to content

Question: How to provide dynamic data to combobox? #52

@coryvirok

Description

@coryvirok

Hello and thanks for taking on HeadlessUI for Svelte! I'm just starting to play around with it and am having some trouble understanding the right way to provide dynamic data to combobox results.

I'd like to use the combobox as an autocomplete for a dynamic form. As the user types, I'll send out an API call to find all of the matching entries and fill in the results in the dropdown as they stream in.

I've tried updating the combobox state directly, e.g. combobox.set({items: itemsFromServer}) whenever the API call finishes. However, I'm not able to use the combobox's filter without ending up in an infinite loop.

What's the right way to go about this?

Thanks!

e.q.

<script lang="ts">
// Autocomplete.svelte

export let filter = ''
export let items: {id: string; name: string; value: any}[] = []
const combobox = createCombobox({filter})

let prevFilter = ''
combobox.subscribe((state) => {
  if (state.filter !== prevFilter) {
    filter = state.filter
  }
})

$: updateCombobox(items)

function updateCombobox(items) {
  combobox.set({ items })
}
</script>

<input use:combobox.input value={$combobox.selected?.name ?? ''} />
<button use:combobox.button type="button" />

<ul use:combobox.items>
  {#each items as value}
    <li use:combobox.item={{ value }} />
  {/each}
</ul>
<script lang="ts">
// +page.svelte

import Autocomplete from './Autocomplete.svelte'

let searchTerm = ''
let items = writable([])

$: updateSearchResults(searchTerm)

function updateSearchResults(searchTerm) {
  makeApiCall(searchTerm).then(results => {
    items.set(results)
  })
}

</script>

<Autocomplete {items} bind:filter={searchTerm} />

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions