react-instantsearch
react-instantsearch copied to clipboard
Offer delay by default at 100 milliseconds for Autocomplete
The autocomplete feature should offer a delay prop, to avoid unnecessary queries when typing fast.
I had to implement it manually like so:
var timeoutId
function delay(t, v) {
return new Promise(function(resolve) {
clearTimeout(timeoutId)
timeoutId = setTimeout(resolve.bind(null, v), t)
});
}
useEffect(() => {
const algoliaClient = algoliasearch(
'***',
'***'
)
const sc = {
async search(requests: any) {
await delay(200);
const shouldSearch = requests.some(
({ params: { query } }: any) => query !== ''
)
if (shouldSearch) {
return algoliaClient.search(requests)
}
return Promise.resolve({
results: [{ hits: [] }],
})
},
searchForFacetValues: algoliaClient.searchForFacetValues,
}
setSearchClient(sc)
}, [])
return (
<InstantSearch
searchClient={searchClient}
indexName="shopify_products"
>
....
This is a standard feature in most Autocomplete modules and a lot of search engines offer a delay :)
Sorry, this is intentional, a debounced search box will give users the perception of a much slower experience than it actually could be.
Aside of that, it's indeed possible to debounce yourself as in the example, although you just delay every call instead of debouncing, that means you're still doing the same amount of queries, just slower.
What you'll want to do more likely is:
https://codesandbox.io/s/fast-currying-3dp59?file=/src/App.js
@Haroenv its slower, but its much cheaper. Algolia charges per search request, 100ms delay is a very reasonable compromise for businesses that have a budget.
Also, i'm not delaying every request, clearTimeout
negates previous requests if the next character is typed. You can see it live and working on our site :) https://www.colabpantry.com.au/