Controlling behavior with State
The state is an underlying set of properties that drives the autocomplete behavior. For example, query contains the value typed in the search input. As the query changes, the retrieved items from the sources change.
The state contains:
query: the search input valueactiveItemId: which item is activecompletion: the completed version of the queryisOpen: whether the autocomplete display panel is open or notstatus: the autocomplete statuscollections: the autocomplete’s collections of itemscontext: the global context passed to lifecycle hooks (see more in Context)
The state is available in all lifecycle hooks so you can customize the behavior.
Setting an initial state
You can instantiate an autocomplete with an initial state via the initialState prop.
1
2
3
4
5
6
7
autocomplete({
  // ...
  initialState: {
    // This uses the `search` query parameter as the initial query
    query: new URL(window.location).searchParams.get('search'),
  },
});
Listening to state changes
State changes occur automatically when a user interacts with the autocomplete (updates the input text, selects an item, etc.). You can react to state changes using the onStateChange lifecycle hook.
1
2
3
4
5
6
autocomplete({
  // ...
  onStateChange({ state }) {
    console.log(state);
  },
});
Manually updating the state
You can also manually update the state using setters. It’s useful to implement custom features on top of autocomplete.
For example, imagine you want to let users fill the search input with the value of a suggestion by clicking or tapping it. You can use the setQuery setter provided by getSources to attach an event when clicking the tap-ahead button and manually set the query.
When using state setters, you should also call refresh to update the UI with fresh sources based on the updated state.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
State
| Parameter | Description | 
|---|---|
          
            activeItemId
          
         | 
        
           
                
                type: number | null
                
               
              
                
                  default: null
                
               
          The highlighted item’s index.  | 
      
          
            query
          
         | 
        
           
                
                type: string
                
               
              
                
                  default: ""
                
               
          The value of the search input.  | 
      
          
            completion
          
         | 
        
           
                
                type: string | null
                
               
              
                
                  default: null
                
               
          The completion of the query.  | 
      
          
            isOpen
          
         | 
        
           
                
                type: boolean
                
               
              
                
                  default: false
                
               
          Whether the panel is open or not.  | 
      
          
            collections
          
         | 
        
           
                
                type: AutocompleteCollection[]
                
               
              
                
                  default: []
                
               
          The collections of items.  | 
      
          
            status
          
         | 
        
           
                
                type: "idle" | "loading" | "stalled" | "error"
                
               
              
                
                  default: "idle"
                
               
          The autocomplete’s status.  | 
      
          
            context
          
         | 
        
           
                
                type: AutocompleteContext
                
               
              
                
                  default: {}
                
               
          The global context passed to lifecycle hooks. See more in Context.  | 
      
Setters
| Parameter | Description | 
|---|---|
          
            setActiveItemId
          
         | 
        
           
                
                type: (value: number | null) => void
                
               
          Sets the highlighted item index. Pass   | 
      
          
            setQuery
          
         | 
        
           
                
                type: (value: string) => void
                
               
          Sets the query.  | 
      
          
            setIsOpen
          
         | 
        
           
                
                type: (value: boolean) => void
                
               
          Sets whether the panel is open or not.  | 
      
          
            setStatus
          
         | 
        
           
                
                type: (value: "idle" | "loading" | "stalled" | "error") => void
                
               
          Sets the status of the autocomplete.  | 
      
          
            setCollections
          
         | 
        
           
                
                type: (value: Collection[]) => void
                
               
          Sets the collections of items of the autocomplete.  | 
      
          
            setContext
          
         | 
        
           
                
                type: (value: AutocompleteContext) => void
                
               
          Sets the context passed to lifecycle hooks. See more in Context.  |