🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
UI libraries / InstantSearch.js / Widgets
Signature
instantsearch({
  indexName: string,
  searchClient: object,
  // Optional parameters
  numberLocale: string,
  searchFunction: function,
  initialUiState: object,
  onStateChange: function,
  stalledSearchDelay: number,
  routing: boolean|object,
  insights: boolean|object,
  insightsClient: function,
  future: {
    preserveSharedStateOnUnmount: boolean,
    persistHierarchicalRootCount: boolean,
  },
});
Import
1
import instantsearch from 'instantsearch.js';

About this widget

You are currently reading the documentation for InstantSearch.js V4. Read our migration guide to learn how to upgrade from V3 to V4. You can still access the V3 documentation for this page.

The instantsearch object is the main component of InstantSearch.js. It manages the widget and lets you add new ones.

Two parameters are required:

  • indexName: your search UI’s main index
  • searchClient: the search client for InstantSearch.js. The search client needs an appId and an apiKey: find those credentials in your Algolia dashboard.

The getting started guide will help you get up and running with InstantSearch.js.

Middleware

InstantSearch.js provides middleware to help you connect to other systems:

Examples

1
2
3
4
5
6
7
8
9
10
11
12
const search = instantsearch({
  indexName: 'instant_search',
  searchClient: algoliasearch(
    'YourApplicationID',
    'YourSearchOnlyAPIKey'
  ),
});

// Add widgets
// ...

search.start();

Options

Parameter Description
indexName
type: string
Required

The main index to search into.

1
2
3
4
const search = instantsearch({
  // ...
  indexName: 'instant_search',
});
searchClient
type: object
Required

Provides a search client to instantsearch. Read the custom backend guidance on implementing a custom search client.

1
2
3
4
5
6
7
const search = instantsearch({
  // ...
  searchClient: algoliasearch(
    'YourApplicationID',
    'YourSearchOnlyAPIKey'
  ),
});
numberLocale
type: string
Optional

The locale used to display numbers. This is passed to Number.prototype.toLocaleString().

1
2
3
4
const search = instantsearch({
  // ...
  numberLocale: 'fr',
});
searchFunction
Deprecated
type: function
Optional

Use onStateChange instead.

This option allows you to take control of search behavior. For example, to avoid doing searches at page load.

When this option is set, search.helper won’t emit events. Instead, use onStateChange or widgets to handle search behavior.

A hook is called each time a search is requested (with Algolia’s search helper as a parameter). Carry out the search by calling helper.search().

When modifying the state of the helper within search-function, the helper resets the page to 0. If you want to keep the current page, you need to store the information about the page, modify the state and reapply the pagination.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const search = instantsearch({
  // ...
  searchFunction(helper) {
    if (helper.state.query) {
      helper.search();
    }
  },
});

// Example which avoids the page resetting to 0
const search = instantsearch({
  // ...
  searchFunction(helper) {
    const page = helper.getPage(); // Retrieve the current page

    helper.setQuery('Hello') // this call resets the page
          .setPage(page) // we re-apply the previous page
          .search();
  }
});
initialUiState
type: object
Optional

Adds a uiState to your instantsearch instance, which provides an initial state to your widgets.

Replace YourIndexName with the name of your Algolia index.

1
2
3
4
5
6
7
8
9
const search = instantsearch({
  // ...
  initialUiState: {
    YourIndexName: {
      query: 'phone',
      page: 5,
    },
  },
});
onStateChange
type: function
Optional

Triggers when the state changes. This can be useful when performing custom logic on a state change.

When using onStateChange, the instance is under your control. You’re responsible for updating the UI state (with setUiState).

1
2
3
4
5
6
7
8
const search = instantsearch({
  // ...
  onStateChange({ uiState, setUiState }) {
    // Custom logic

    setUiState(uiState);
  },
});
stalledSearchDelay
type: number
default: 200
Optional

A time period (in ms) after which the search is considered to have stalled. Read the slow network guide for more information.

1
2
3
4
const search = instantsearch({
  // ...
  stalledSearchDelay: 500,
});
routing
type: boolean|object
default: false
Optional

The router configuration used to save the UI state into the URL or any client-side persistence. The object is accepted if it has either of these keys:

  • router: object: this object is the part that saves the UI state. By default, it uses an instance of the history with the default parameters. It accepts:
    • onUpdate: function: adds an event listener that makes InstantSearch aware of external changes to the storage medium (such as the URL). Typically you’ll set up a listener for popstate, which triggers a callback with the current routeState.
    • read: function: reads the routing storage and gets routeState. It doesn’t take any parameters but returns an object.
    • write: function: pushes routeState into routing storage.
    • createURL: function: transforms routeState into a URL. It receives an object and returns a string (which may be empty).
    • dispose: function: cleans up all event listeners.
  • stateMapping: object: transforms the uiState into the object saved by the router. The default value is provided by simple. It accepts:
    • stateToRoute: function: transforms a ui-state representation into routeState. It receives an object that contains the UI state of all the widgets on the page. It can return any object that is readable by routeToState.
    • routeToState: function: transforms routeState into a ui-state representation. It receives an object that contains the UI state stored by the router. It can return any object that is readable by stateToRoute.

For more information, read the routing guide.

1
2
3
4
const search = instantsearch({
  // ...
  routing: true,
});
insights
since: v4.55.0
type: boolean|object
default: false
Optional

Enables the Insights middleware and loads the search-insights library (if not already loaded). The Insights middleware sends view and click events automatically, and lets you set up your own click and conversion events.

To use this option with an object, refer to the Insights middleware options.

1
2
3
4
const search = instantsearch({
  // ...
  insights: true,
});
insightsClient
Deprecated
type: function
Optional

Use insights instead.

This function is exposed by the search-insights library (usually window.aa) and is required for sending click and conversion events with the insights middleware.

1
2
3
4
const search = instantsearch({
  // ...
  insightsClient: window.aa
});
future
type: object
Optional

This option lets you try out new InstantSearch features without affecting the current experience for everyone else.

See below for more information on individual future options.

preserveSharedStateOnUnmount
since: v4.58.0
type: boolean
default: false
Optional

Changes the way dispose is used in the InstantSearch lifecycle.

If false (the default), each widget unmounting will also remove its state, even if multiple widgets read that UI state.

If true, each widget unmounting will only remove its state if it’s the last of its type. This allows you to dynamically add and remove widgets without losing their state.

1
2
3
4
5
6
const search = instantsearch({
  // ...
  future: {
    preserveSharedStateOnUnmount: true,
  },
});
persistHierarchicalRootCount
since: v4.62.0
type: boolean
default: false
Optional

Whether to display a constant facet value count at the root of a hierarchical menu with active refinements.

If false (default), the facet value count at the root level shows the facet value count of the refined (child) facet’s parent.

If true, the facet value count at the root level shows the sum of the facet value counts of all its children, with or without refined children.

1
2
3
4
5
6
const search = instantsearch({
  // ...
  future: {
    persistHierarchicalRootCount: true,
  },
});

Methods

Parameter Description
addWidgets

Adds widgets to the instantsearch instance.

You can add widgets to instantsearch before and after you start it.

1
2
3
4
5
6
7
8
9
10
11
12
13
const search = instantsearch({
  // ...
});

const searchBox = instantsearch.widgets.searchBox({
  // ...
});

const hits = instantsearch.widgets.hits({
  // ...
});

search.addWidgets([searchBox, hits]);
addWidget
Deprecated

Use addWidgets([widget]) instead.

Adds a widget to the instantsearch instance.

You can add widgets to instantsearch before and after you start it.

1
2
3
4
5
6
7
8
9
const search = instantsearch({
  // ...
});

const searchBox = instantsearch.widgets.searchBox({
  // ...
});

search.addWidget(searchBox);
start

Finalizes the setup of instantsearch and triggers the first search.

Call this method after you have added all your required widgets to instantsearch. You can also add widgets after instantsearch has started, but these widgets aren’t considered during searches made before you add them.

1
2
3
4
5
const search = instantsearch({
  // ...
});

search.start();
removeWidgets

Removes widgets from the instantsearch instance. You can only do this after you start instantsearch.

The widgets you remove from instantsearch must implement a dispose() method to reset the search parameters they manage.

1
2
3
4
5
6
7
8
9
10
11
12
13
const search = instantsearch({
  // ...
});

const searchBox = instantsearch.widgets.searchBox({
  // ...
});

const hits = instantsearch.widgets.hits({
  // ...
});

search.removeWidgets([searchBox, hits]);
removeWidget
Deprecated

Removes a widget from the instantsearch instance. You can only do this after you start instantsearch.

The widget you remove from instantsearch must implement a dispose() method to reset the search parameters they manage.

1
2
3
4
5
6
7
8
9
const search = instantsearch({
  // ...
});

const searchBox = instantsearch.widgets.searchBox({
  // ...
});

search.removeWidget(searchBox);
dispose

Removes all widgets from the instance. This method doesn’t trigger a search.

1
2
3
4
5
const search = instantsearch({
  // ...
});

search.dispose();
setUiState

Injects a uiState into the instance without relying on internal events (such as connectors’ refine or widget interactions).

For this option to work, the widgets responsible for each UI state attribute need to be mounted. For instance, a searchBox is necessary to provide a query.

1
2
3
4
5
6
7
8
9
10
11
12
const search = instantsearch({
  // ...
});

search.start();

search.setUiState({
  // Replace instant_search with your index name
  instant_search: {
    query: 'phone'
  }
});
refresh

Clears the Algolia responses cache and triggers a new search. For more information, read the InstantSearch caching guide.

1
2
3
4
5
const search = instantsearch({
  // ...
});

search.refresh();

Properties

Parameter Description
status
type: "idle" | "loading" | "stalled" | "error"

The status of the in-progress search.

Possible values are:

  • 'idle': no search is in progress.
  • 'loading': the search is loading. Use loading for immediate feedback on an action. For loading indicators, use 'stalled' instead.
  • 'stalled': the search is stalled. This gets triggered after stalledSearchDelay expires.
  • 'error': the search failed. The error is available in the error property.
1
2
3
4
5
6
7
8
9
const search = instantsearch({
  // ...
});

search.start();

search.on('render', () => {
  console.log(search.status);
});
error
type: Error | undefined

The error that occurred during the search. This is only defined when status is 'error'.

1
2
3
4
5
6
7
8
9
10
11
12
const search = instantsearch({
  // ...
});

search.start();

// add an error handler to prevent uncaught errors
search.on('error', () => {});

search.on('render', () => {
  console.log(search.status === 'error' && search.error);
});
renderState
type: RenderState | undefined

The renderState provides access to all the data to render the widgets, including the methods to refine the search. More information can be found in the renderState page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const indexName = '<index-name>';
const search = instantsearch({
  indexName,
  // ...
});
search.addWidgets([
  searchBox({
    container: '<your-container>',
  }),
]);
search.start();

console.log(search.renderState[indexName].searchBox);
/*
  {
    query: string;
    refine: Function;
    clear: Function;
    isSearchStalled: boolean;
    widgetParams: object;
  }
*/

Events

Parameter Description
render

Fires when all widgets are rendered. This happens after every search request.

1
2
3
4
5
6
7
const search = instantsearch({
  // ...
});

search.on('render', () => {
  // Do something on render
});
error

Fires when calling the API reports an error.

1
2
3
4
5
6
7
const search = instantsearch({
  // ...
});

search.on('error', ({ error }) => {
  // Do something on error
});
Did you find this page helpful?