instantsearch | InstantSearch.js | Algolia (2023)

Signature

instantsearch({ indexName: string, searchClient: object,  // Optional parameters numberLocale: string, searchFunction: function, initialUiState: object, onStateChange: function, stalledSearchDelay: number, routing: boolean|object, insightsClient: function,});

Import

Copy

(Video) What is Algolia

1
import instantsearch from 'instantsearch.js';
1
window.instantsearch
(Video) Getting started with React InstantSearch

See code examples

(Video) Discover Algolia #1 - When To Use (and not to use) Algolia

About thiswidget

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:

  • Insights. Use the insights middleware to send click and conversion events
  • Generic. With the middleware API, you can inject functionality into InstantSearch.js. For example, to send events to Google Analytics.

Examples

Copy

123456789101112
const search = instantsearch({ indexName: 'instant_search', searchClient: algoliasearch( 'YourApplicationID', 'YourSearchOnlyAPIKey' ),});// Add widgets// ...search.start();
(Video) Fullstack Autocomplete Search with Algolia

Options

indexName

type: string

Required

The main index to search into.

Copy

1234
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.

Copy

1234567
const search = instantsearch({ // ... searchClient: algoliasearch( 'YourApplicationID', 'YourSearchOnlyAPIKey' ),});
numberLocale

type: string

Optional

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

Copy

1234
const search = instantsearch({ // ... numberLocale: 'fr',});
searchFunction

type: function

Optional

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 on-state-change or widgets to handle search behavior.

A hook is called each time a search is requested (with Algolia’s helper API 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.

Copy

1234567891011121314151617181920
const search = instantsearch({ // ... searchFunction(helper) { if (helper.state.query) { helper.search(); } },});// Example which avoids the page resetting to 0const 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. To apply the uiState to the search parameters, you must add your widgets to your instantsearch instance.

Copy

123456789
const search = instantsearch({ // ... initialUiState: { indexName: { 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 on-state-change, the instance is under your control. You’re responsible for updating the UI state (with setUiState).

Copy

12345678
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.

Copy

1234
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.

Copy

1234
const search = instantsearch({ // ... routing: true,});
1234567
const search = instantsearch({ // ... routing: { router: instantsearch.routers.history(), stateMapping: instantsearch.stateMappings.simple(), },});
insightsClient

type: function

Optional

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.

Copy

1234
const search = instantsearch({ // ... insightsClient: window.aa});

Methods

addWidgets

Adds widgets to the instantsearch instance.

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

Copy

12345678910111213
const search = instantsearch({ // ...});const searchBox = instantsearch.widgets.searchBox({ // ...});const hits = instantsearch.widgets.hits({ // ...});search.addWidgets([searchBox, hits]);
addWidget

Adds a widget to the instantsearch instance.

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

This method is deprecated. Use addWidgets([widget]) instead.

Copy

123456789
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.

Copy

12345
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.

Copy

12345678910111213
const search = instantsearch({ // ...});const searchBox = instantsearch.widgets.searchBox({ // ...});const hits = instantsearch.widgets.hits({ // ...});search.removeWidgets([searchBox, hits]);
removeWidget

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.

This method is deprecated. Use removeWidgets([widget]) instead.

Copy

123456789
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.

Copy

12345
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.

Copy

123456789101112
const search = instantsearch({ // ...});search.start();search.setUiState({ // Replace instant_search with your index name instant_search: { query: 'phone' }});
12345678910111213141516
const search = instantsearch({ // ...});search.start();search.setUiState(uiState => { return { ...uiState, // Replace instant_search with your own index name instant_search: { ...uiState.instant_search, query: 'phone' } }});
refresh

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

Copy

12345
const search = instantsearch({ // ...});search.refresh();
(Video) FlutterFlow: Build A Search Engine with Firebase Firestore and Algolia (2022) | FlutterFlow 2022

Properties

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.

Copy

123456789
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'.

Copy

123456789101112
const search = instantsearch({ // ...});search.start();// add an error handler to prevent uncaught errorssearch.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.

Copy

12345678910111213141516171819202122
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

render

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

Copy

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

Fires when calling the API reports an error.

Copy

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

Videos

1. Alcoholia (Full Video) Vikram Vedha | Hrithik, Saif | Vishal-Sheykhar, Manoj M | Snigdhajit, Ananya
(T-Series)
2. 7 ways to get more out of Algolia Search
(Algolia)
3. Implement Algolia in 4 steps
(Algolia)
4. Typesense vs Algolia & Elasticsearch
(Changelog)
5. Alcoholia:Vikram Vedha | Hrithik Roshan, Saif Ali Khan | Vishal-Sheykhar, Manoj M |Snigdhajit,Ananya
(T-Series)
6. Display Algolia search results with vue-instantsearch
(Cleavr)
Top Articles
Latest Posts
Article information

Author: Otha Schamberger

Last Updated: 21/06/2023

Views: 5859

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Otha Schamberger

Birthday: 1999-08-15

Address: Suite 490 606 Hammes Ferry, Carterhaven, IL 62290

Phone: +8557035444877

Job: Forward IT Agent

Hobby: Fishing, Flying, Jewelry making, Digital arts, Sand art, Parkour, tabletop games

Introduction: My name is Otha Schamberger, I am a vast, good, healthy, cheerful, energetic, gorgeous, magnificent person who loves writing and wants to share my knowledge and understanding with you.