> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Controlling behavior with state

> The state object determines the behavior of Autocomplete.

<Tip>
  Autocomplete is also available as an experimental widget in InstantSearch,
  making it easier to integrate into your search experience.
  For more information,
  see the API reference for [InstantSearch.js](/doc/api-reference/widgets/autocomplete/js) or
  [React InstantSearch](/doc/api-reference/widgets/autocomplete/react).
</Tip>

See also: [Implement multiple search states](/doc/ui-libraries/autocomplete/guides/implementing-multiple-search-states)

## Set an initial state

Initialize the Autocomplete state with the [`initialState`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete#param-initial-state) prop.

```js JavaScript icon=code theme={"system"}
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`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete#param-on-state-change) lifecycle hook.

```js JavaScript icon=code theme={"system"}
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](#setters).
For example, to let users fill the search box with a selected [Query Suggestion](/doc/ui-libraries/autocomplete/api-reference/autocomplete-plugin-query-suggestions/createQuerySuggestionsPlugin), use [`setQuery`](#param-set-query).

**When using state setters, call [`refresh`](/doc/ui-libraries/autocomplete/api-reference/autocomplete-js/autocomplete#param-refresh)** to update the UI with fresh [sources](/doc/ui-libraries/autocomplete/core-concepts/sources) based on the updated state.

<CodeGroup>
  ```js JavaScript theme={"system"}
  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>`;
            },
          },
        },
      ];
    },
  });
  ```

  ```jsx JSX theme={"system"}
  /** @jsx h */
  import { h } from "preact";
  import { autocomplete } from "@algolia/autocomplete-js";

  autocomplete({
    // ...
    getSources({ setQuery, refresh }) {
      return [
        {
          // ...
          templates: {
            item({ item }) {
              return (
                <div className="aa-ItemContent">
                  <div className="aa-ItemSourceIcon">Icon</div>
                  <div className="aa-ItemTitle">{item.query}</div>
                  <button
                    className="aa-ItemActionButton"
                    onClick={(event) => {
                      event.stopPropagation();

                      setQuery(item.query);
                      refresh();
                    }}
                  >
                    Fill query
                  </button>
                </div>
              );
            },
          },
        },
      ];
    },
  });
  ```
</CodeGroup>

## Reference

The state object changes as users interact with Autocomplete but you can also change the state with [setters](#setters).

### State object

The state object is available in all lifecycle hooks.

<ParamField body="activeItemId" type="number | null" post={["default: null"]}>
  The active (highlighted) item.
</ParamField>

<ParamField body="query" type="string" default="">
  The search input value.
  As the query changes, the items retrieved from sources also change.
</ParamField>

<ParamField body="completion" type="string | null" post={["default: null"]}>
  The completed version of the query.
</ParamField>

<ParamField body="isOpen" type="boolean" default={false}>
  Whether the Autocomplete display panel is open or not.
</ParamField>

<ParamField body="collections" type="AutocompleteCollection[]" default={[]}>
  The Autocomplete collection of items.
</ParamField>

<ParamField body="status" type="&#x22;idle&#x22; | &#x22;loading&#x22; | &#x22;stalled&#x22; | &#x22;error&#x22;" default="idle">
  The Autocomplete status.
</ParamField>

<ParamField body="context" type="AutocompleteContext" default={{}}>
  The global context passed to lifecycle hooks.
  For more information, see [Context](/doc/ui-libraries/autocomplete/core-concepts/context).
</ParamField>

### Setters

<ParamField body="setActiveItemId" type="(value: number | null) => void">
  Sets the active (highlighted) item. `null` clears the selection.
</ParamField>

<ParamField body="setQuery" type="(value: string) => void">
  Sets the query.
</ParamField>

<ParamField body="setIsOpen" type="(value: boolean) => void">
  Sets whether the Autocomplete display panel is open or not.
</ParamField>

<ParamField body="setStatus" type="(value: &#x22;idle&#x22; | &#x22;loading&#x22; | &#x22;stalled&#x22; | &#x22;error&#x22;) => void">
  Sets Autocomplete status.
</ParamField>

<ParamField body="setCollections" type="(value: Collection[]) => void">
  Sets the Autcomplete collection of items.
</ParamField>

<ParamField body="setContext" type="(value: AutocompleteContext) => void">
  Sets the context passed to lifecycle hooks.
  For more information, see [Context](/doc/ui-libraries/autocomplete/core-concepts/context).
</ParamField>
