Search code examples
typescriptdebouncingngxs

How to implement Debounce analog for ngxs action?


I have search input:

<input type="text" (ngModelChange)="projectFilter()">

When user is typing It will call projectFilter function after every model change.

How can I implement Debounce with ngxs?

for example dispatch actions only after 0.5 sec after user finish typing?

  projectFilter() {
      this.store.dispatch([
        new SomeAction()
      );
    });
  }

Solution

  • One way to do this would be to create an observable chain using a BehaviorSubject that dispatches the action with debounceTime().

    // somewhere in your component class
    projectFilter$ = new BehaviorSubject<string>('')
    
    projectFilter() {
      // set next value instead of dispatching
      this.projectFilter$.next('current value')
    }
    
    ngOnInit() {
        // debounce whenever a new value is available with debounce
        this.projectFilter$.pipe(
          debounceTime(1000),
          tap(() => {
            this.store.dispatch(new MyAction())
          })
        ).subscribe()
    }
    

    Note: Code not tested. Just use it to understand the concept & implement accordingly.

    Alternatively, you might want to use reactive forms. With that, you get things like valueChanges as an observable for free.

    Hope this helps.