Hi all!
I’m having an issue to make debounce work when using Autocomplete with Instantsearch using this guide and this one for debounce
Everything works properly, but all the queries are sent to Algolia immediately without waiting for debounce. My goal is to limit the number of queries by using debounce. The problem appeared when adding instant search, it worked perfectly when autocomplete was standalone.
I think the problem comes from:
onStateChange({ prevState, state }) {
if (prevState.query !== state.query) {
setInstantSearchUiState({ query: state.query })
}
},
but I couldn’t figure out what’s the issue.
Anyone has an idea? Thanks in advance!
Full autocomplete function
autocomplete({
container: '#autocomplete',
placeholder: 'Search for simulations',
detachedMediaQuery: 'none',
// You want recent searches to appear with an empty query.
openOnFocus: true,
// Add the recent searches plugin.
plugins: [recentSearchesPlugin],
onStateChange({ prevState, state }) {
if (prevState.query !== state.query) {
debouncedSetInstantSearchUiState({ query: state.query })
}
},
initialState: {
query: searchPageState.query || '',
},
onSubmit({ state }) {
setInstantSearchUiState({ query: state.query })
},
onReset() {
setInstantSearchUiState({ query: '' })
},
onStateChange({ prevState, state }) {
if (prevState.query !== state.query) {
setInstantSearchUiState({ query: state.query })
}
},
getSources({ query }) {
return debounced([
{
sourceId: 'products',
onSelect({ item }) {
window.location.assign(`/simulations/${item.Slug}`)
},
getItemUrl({ item }) {
return `/simulations/${item.Slug}`
},
getItems() {
return getAlgoliaResults({
searchClient,
queries: [
{
indexName: INSTANT_SEARCH_INDEX_NAME,
query,
params: {
hitsPerPage: 5,
attributesToSnippet: ['Name:10', 'Short_description:35'],
snippetEllipsisText: '…',
},
},
],
});
},
templates: {
noResults() {
return 'No results.';
},
item({ item, components, html }) {
return html`<div class="aa-ItemWrapper">
<div class="aa-ItemContent">
<div class="aa-ItemContentBody">
<div class="aa-ItemContentTitle">
${components.Highlight({
hit: item,
attribute: 'Name',
})}
</div>
<div class="aa-ItemContentDescription">
${components.Snippet({
hit: item,
attribute: 'Short_description',
})}
</div>
</div>
</div>
</div>`;
},
},
},
]);
},
});