autocomplete
autocomplete copied to clipboard
LocalStorageRecentSearchesPlugin not working with other hooks than onSubmit
Description
You can’t use LocalStorageRecentSearchesPlugin with autocomplete option defaultActiveItemId (e.g. defaultActiveItemId: 0), because onSubmit lifecycle hook is not fired by autocomplete in this case. LocalStorageRecentSearchesPlugin is based on this hook. It would be good to have the choice, which lifecycle hooks trigger the plugin. In practice also onSelect is needed, but it’s currently only for querySuggestionsPlugin implemented: https://github.com/algolia/autocomplete/blob/dc8b6f2b585d0992bcb22d2c61053388c1c90590/packages/autocomplete-plugin-recent-searches/src/createRecentSearchesPlugin.ts#L57
PS: It's unclear, whether incompatibility with defaultActiveItemId is intended behavior or a bug. At least it's very confusing and not mentioned anywhere in the docs.
Expected behavior
LocalStorageRecentSearchesPlugin should handle onSubmit and onSelect hook. At least, it should be mentioned in the docs, if it's not possible.
Environment
- Autocomplete version: 1.7.1
This is a workaround written in plain ES6+, which works for me at the moment:
import { createLocalStorageRecentSearchesPlugin } from '@algolia/autocomplete-plugin-recent-searches'
import { createLocalStorage } from '@algolia/autocomplete-plugin-recent-searches/dist/esm/createLocalStorage'
import { LOCAL_STORAGE_KEY } from '@algolia/autocomplete-plugin-recent-searches/dist/esm/constants'
const storage = createLocalStorage({
key: `${LOCAL_STORAGE_KEY}:my_search`,
limit: 5
})
const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
key: 'my_search',
subscribe: ({ onSelect }) => {
onSelect(({ item }) => {
storage.onRemove(item.id)
storage.onAdd(item)
})
}
})
recentSearchesPlugin.storage = storage