wire-elements / spotlight

Livewire component that brings Spotlight/Alfred-like functionality to your Laravel application.
MIT License
925 stars 72 forks source link

Scoped dependency searching executes a query on every keystroke #60

Closed LTKort closed 2 years ago

LTKort commented 2 years ago

If I use the example;

public function searchTeam($query)
  {
      return Team::where('name', 'like', "%$query%")
          ->get()
          ->map(function(Team $team) {
              return new SpotlightSearchResult(
                  $team->id,
                  $team->name,
                  sprintf('Create user for %s', $team->name)
              );
          });
  }

It does a query every keystroke, is there a way to fix this?

pavlentij commented 2 years ago

The simplest way is to add timeout before the searchDependency request.

You can do it by customizing spotlight.js file. Find lines from the line 25:

            this.$watch('input', value => {
                if (value.length === 0) {
                    this.selected = 0;
                }
                if(this.selectedCommand !== null && this.currentDependency !== null && this.currentDependency.type === 'search'){
                    this.$wire.searchDependency(this.selectedCommand.id, this.currentDependency.id, value, this.resolvedDependencies);
                }
            });

and replace it with:

            this.$watch('input', value => {
                if (value.length === 0) {
                    this.selected = 0;
                }
                if(this.selectedCommand !== null && this.currentDependency !== null && this.currentDependency.type === 'search'){
                    var delayTimer, _this = this;

                    clearTimeout(delayTimer);

                    delayTimer = setTimeout(function() {
                        _this.$wire.searchDependency(_this.selectedCommand.id, _this.currentDependency.id, value, _this.resolvedDependencies);
                    }, 300);
                }
            });

After the changes the spotlight will make a request only after the 300ms and if you are typing a word then it will not do multiple requests for every single letter.

PhiloNL commented 2 years ago

If you publish the view you can update the x-model binding to include the .debounce modifier.