UI libraries / Autocomplete / API reference / autocomplete-plugin-recent-searches

createLocalStorageRecentSearchesPlugin

The createLocalStorageRecentSearchesPlugin plugin connects with the user’s local storage to fetch and save recent searches To use your storage, see createRecentSearchesPlugin.

Installation

  1. Install the plugin:

    1
    2
    3
    
     yarn add @algolia/autocomplete-plugin-recent-searches
     # or
     npm install @algolia/autocomplete-plugin-recent-searches
    
  2. Import the plugin into your project:

    1
    
     import { createLocalStorageRecentSearchesPlugin } from '@algolia/autocomplete-plugin-recent-searches';
    

    If you don’t use a package manager, use the HTML script element:

    1
    2
    3
    4
    5
    6
    
     <script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-plugin-recent-searches@1.18.1/dist/umd/index.production.js" integrity="sha256-61LUp5dwCyEdHQJM4SSmtLDU/uTzlLvaVXzYoGp5yVo=" crossorigin="anonymous"></script>
     <script>
       const { createLocalStorageRecentSearchesPlugin } = window[
         '@algolia/autocomplete-plugin-recent-searches'
       ];
     </script>
    

Example

This example uses the plugin within autocomplete-js.

1
2
3
4
5
6
7
8
9
10
11
12
import { autocomplete } from '@algolia/autocomplete-js';
import { createLocalStorageRecentSearchesPlugin } from '@algolia/autocomplete-plugin-recent-searches';

const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
  key: 'navbar',
});

autocomplete({
  container: '#autocomplete',
  openOnFocus: true,
  plugins: [recentSearchesPlugin],
});

You can combine this plugin with the Query Suggestions plugin to populate the empty screen with recent and popular queries.

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
import { liteClient as algoliasearch } from 'algoliasearch/lite';
import { autocomplete } from '@algolia/autocomplete-js';
import { createLocalStorageRecentSearchesPlugin } from '@algolia/autocomplete-plugin-recent-searches';
import { createQuerySuggestionsPlugin } from '@algolia/autocomplete-plugin-query-suggestions';

const searchClient = algoliasearch(
  'latency',
  '6be0576ff61c053d5f9a3225e2a90f76'
);
const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
  key: 'navbar',
});
const querySuggestionsPlugin = createQuerySuggestionsPlugin({
  searchClient,
  indexName: 'instant_search_demo_query_suggestions',
  getSearchParams() {
    return recentSearchesPlugin.data.getAlgoliaSearchParams();
  },
});

autocomplete({
  container: '#autocomplete',
  openOnFocus: true,
  plugins: [recentSearchesPlugin, querySuggestionsPlugin],
});

Parameters

key
type: string
Required

A local storage key to identify where to save and retrieve the recent searches.

For example:

  • "navbar"
  • "search"
  • "main"

The plugin namespaces all keys to avoid collisions.

limit
type: number

The number of recent searches to display.

type: (params: { query: string; items: TItem[]; limit: number; }) => TItem[]

A search function to retrieve recent searches from. This function is called in storage.getAll to retrieve recent searches and is useful to filter and highlight recent searches when typing a query.

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
function highlight({ item, query }) {
  return {
    ...item,
    _highlightResult: {
      query: {
        value: query
          ? item.query.replace(
              new RegExp(query, 'g'),
              `<span class='underline'>aa-highlight</span>${query}<span class='underline'>/aa-highlight</span>`
            )
          : item.query,
      },
    },
  };
}

function search({ query, items, limit }) {
  if (!query) {
    return items.slice(0, limit).map((item) => highlight({ item, query }));
  }

  return items
    .filter((item) => item.query.toLowerCase().includes(query.toLowerCase()))
    .slice(0, limit)
    .map((item) => highlight({ item, query }));
}
transformSource
type: (params: { source: AutocompleteSource, state: AutocompleteState, onRemove: () => void, onTapAhead: () => void })

This function takes the original source as a parameter and returns a modified version of that source. For example:

Change Autocomplete state

Usually, when a link in the Autocomplete menu is selected, the menu closes. However, to keep the menu visible after a selection is made, use transformSource to set the isOpen state:

1
2
3
4
5
6
7
8
9
10
11
const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
  key: 'navbar',
  transformSource({ source, onRemove }) {
    return {
      ...source,
      onSelect({ setIsOpen }) {
        setIsOpen(true);
      },
    };
  },
});

Create links

Turns Query Suggestions into clickable Google search links:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
  key: 'navbar',
  transformSource({ source, onRemove }) {
    return {
      ...source,
      getItemUrl({ item }) {
        return `https://google.com?q=${item.query}`;
      },
      templates: {
        ...source.templates,
        item(params) {
          const { item, html } = params;

          return html`<a
            class="aa-ItemLink"
            href="https://google.com?q=${item.query}"
          >
            ${source.templates.item(params).props.children}
          </a>`;
        },
      },
    };
  },
});
translations
type: AutocompleteRecentSearchesPluginTranslations

A dictionary of translations to support internationalization.

1
2
3
4
type AutocompleteRecentSearchesPluginTranslations = {
  removeSearchTitle: string; // defaults to 'Remove this search'
  fillQueryTitle: (text: string) => string; // defaults to 'Fill query with "${text}"'
}

Returns

data

getAlgoliaSearchParams
type: SearchParameters => SearchParameters

Optimized Algolia search parameters. This is useful when using the plugin along with the Query Suggestions plugin.

This function enhances the provided search parameters by:

  • Excluding Query Suggestions that are already displayed in recent searches.
  • Using a shared hitsPerPage value to get a group limit of Query Suggestions and recent searches.
addItem
type: (item: TItem) => void

A function that adds an item to the recent searches local storage.

removeItem
type: (id: string) => void

A function that removes an item from the recent searches local storage.

getAll
type: () => TItem[]

A function that returns the items from the recent searches local storage.

Did you find this page helpful?