Autocomplete is also available as an experimental widget in InstantSearch, making it easier to integrate into your search experience.
To learn more, see the API reference for InstantSearch.js or React InstantSearch.
See also: Implement multiple search states
Set an initial state
Initialize the Autocomplete state with the initialState prop.
autocomplete({
// ...
initialState: {
// This uses the 'search' query parameter as the initial query
query: new URL(window.location).searchParams.get("search"),
},
});
Listen to state changes
The state changes when users interact with Autocomplete (for example, by updating the search box text or selecting an item).
Watch for these changes and respond to them by passing the state object to the onStateChange lifecycle hook.
autocomplete({
// ...
onStateChange({ state }) {
// Custom code reacting to state changes
console.log("The Autocomplete state has changed:", state);
},
});
Update the state
Update the state with setters.
For example, to let users fill the search box with a selected Query Suggestion, use setQuery.
When using state setters, call refresh to update the UI with fresh sources based on the updated state.
import { autocomplete } from "@algolia/autocomplete-js";
autocomplete({
// ...
getSources({ setQuery, refresh }) {
return [
{
// ...
templates: {
item({ item, html }) {
return html`<div class="aa-ItemContent">
<div class="aa-ItemSourceIcon">Icon</div>
<div class="aa-ItemTitle">${item.query}</div>
<button
class="aa-ItemActionButton"
onClick="${(event) => {
event.stopPropagation();
setQuery(item.query);
refresh();
}}"
>
Fill query
</button>
</div>`;
},
},
},
];
},
});
Reference
The state object changes as users interact with Autocomplete but you can also change the state with setters.
State object
The state object is available in all lifecycle hooks.
activeItemId
number | null
default: null
The active (highlighted) item.
The search input value.
As the query changes, the items retrieved from sources also change.
completion
string | null
default: null
The completed version of the query.
Whether the Autocomplete display panel is open or not.
collections
AutocompleteCollection[]
default:[]
The Autocomplete collection of items.
status
"idle" | "loading" | "stalled" | "error"
default:"idle"
The Autocomplete status.
context
AutocompleteContext
default:{}
The global context passed to lifecycle hooks.
For more information, see Context.
Setters
setActiveItemId
(value: number | null) => void
Sets the active (highlighted) item. null clears the selection.
Sets whether the Autocomplete display panel is open or not.
setStatus
(value: "idle" | "loading" | "stalled" | "error") => void
Sets Autocomplete status.
setCollections
(value: Collection[]) => void
Sets the Autcomplete collection of items.
setContext
(value: AutocompleteContext) => void
Sets the context passed to lifecycle hooks.
For more information, see Context.