How to handle selecting an autocomplete result? onSelect?

What’s the recommended way to handle selecting an autocomplete result (i.e. either via mouse click or enter on the keyboard)?

I’m assuming you’re supposed to do it with onSelect, within the autocomplete function. I currently have:

const autocomplete = useMemo(() =>
    createAutocomplete({
      onStateChange({ state }) {
        // Synchronize the Autocomplete state with the React state.
        setAutocompleteState(state);
      },
      getSources() {
        return [
          {
            ...
            getItems({ query }) {
              ...
            },
            onSelect({ state, event }) {
              console.log(event.target);
            }
          },
        ];
      },
    }),
  []);

However when I click on something (and onSelect gets triggered) the whole autocomplete state gets wiped, so I can’t access anything within it. I’d like to be able to do something like:

onSelect({ state, event }) {
  const activeItem = state.activeItemId;
  console.log(state.collections[0].items[activeItem];
}

Because I already have the data in the app, I could avoid having to query Algolia all over again.

Ok, figured it out. Need to use the onSelect parameter of autocomplete: Populating autocomplete with Sources | Autocomplete | Algolia

Looks like this:

const autocomplete = useMemo(() =>
    createAutocomplete({
      onStateChange({ state }) {
        // Synchronize the Autocomplete state with the React state.
        setAutocompleteState(state);
      },
      getSources() {
        return [
          {
            ...
            getItems({ query }) {
              ...
            },
            onSelect: function(event) {
              event.setQuery(event.item.name);
              console.log(event.item);
            },
          },
        ];
      },
    }),
  []);
1 Like