react-instantsearch icon indicating copy to clipboard operation
react-instantsearch copied to clipboard

Offer delay by default at 100 milliseconds for Autocomplete

Open achadee opened this issue 3 years ago • 2 comments

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

achadee avatar Aug 05 '21 22:08 achadee

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 avatar Aug 06 '21 07:08 Haroenv

@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/

achadee avatar Aug 07 '21 22:08 achadee