algolia / instantsearch

⚡️ Libraries for building performant and instant search and recommend experiences with Algolia. Compatible with JavaScript, TypeScript, React and Vue.
https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/js/
MIT License
3.7k stars 516 forks source link

Offer delay by default at 100 milliseconds for Autocomplete #5251

Closed achadee closed 2 months ago

achadee commented 3 years ago

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 :)

Haroenv commented 3 years ago

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

achadee commented 3 years ago

@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