0

I implemented Algolia in my project like in this example (without the filter) and it is working.

Now I would like to add a debounce so I do not search on every key stroke, but wait for example 500ms until search. That timer is reset if the user types in another letter.

I am using the suggested HitsSearcher which has a debounce field, but changing that, didn't change anything for me. The results were still displayed instantly.

I also tried implementing this with a timer, and this causes the pause but after that pause, it is fired as often as new changes came in. So the timer is never actually cancelled.

In my init:

_searchTextEditingController.addListener(
  () => _startTimer(),
);

and _startTimer():

 _startTimer() {
    _timer = Timer(
      const Duration(milliseconds: 2000),
      () {
        print('finished');
        _userSearcher.applyState(
          (state) => state.copyWith(
            query: _searchTextEditingController.text,
            page: 0,
          ),
        );
      },
    );
  }

So how can I achieve this? Im doing this to reduce the search requests on algolia.

Let me know if you need any more info!

EDIT

This question is not solved by the suggested question. Debounce is not working correctly and giving me wrong search results.

Chris
  • 1,828
  • 6
  • 40
  • 108

1 Answers1

1

I had to remove the addListener and instead use the suggested answer from the suggested question and put it inside my onChanged. My _onSearchChanged now looks like this:

  _onSearchChanged(String query) {
    if (_debounce?.isActive ?? false) {
      _debounce?.cancel();
    }

    _debounce = Timer(const Duration(milliseconds: 500), () {
      _userSearcher.applyState(
        (state) => state.copyWith(
          query: _searchTextEditingController.text,
          page: 0,
        ),
      );
    });
  }
Chris
  • 1,828
  • 6
  • 40
  • 108