1

Hi using React and I've got this code in a component that does a query when an external entity name changes. So it comes from another input somewhere in the app. When it change my other component gets update and run that request. The external input is already debounce at 250ms, but I want to debounce this code to make sure I don't sent too much request to server for nothing. I use debounceTime(5000) there to test it, but it just happen instantly. My server is local for now, so it's very fast to get a response. I wonder what I'm doing wrong with the debounceTime function.

    const url = formField.getRequest(entity);
    const headers = Headers.getDefaultHeaders(context);
    headers.Accept = 'application/json';
    headers['Content-Type'] = 'application/json';
    ajaxObservable = ajax({
      url,
      method: 'get',
      headers,
    }).pipe(
      debounceTime(5000),
      map((response) => {
        const options = formField.parseResponse(response.response);
        doneCB(options.sort());
      }),
      catchError(() => of({})),
    );

    ajaxObservable.subscribe(() => {});```

Thanks a lot!
ThePainnn
  • 381
  • 1
  • 5
  • 17
  • You are probably creating a new chain for each change. The same problem https://stackoverflow.com/questions/41935424/how-to-achieve-a-debounce-service-on-input-keyup-event-in-angular2-with-rxjs/41965515#41965515 – martin Apr 09 '20 at 22:25
  • 1
    There is no need to add `debounceTime` here, as you are already debouncing the input – wentjun Apr 10 '20 at 05:07
  • There is a need. Sometimes the input might be debounced sometimes not. It's all part of an framework that generates page based on data driven calls. So yes, sometimes it will be debounced sometimes not. Sorry if it was not clear in the question. – ThePainnn Apr 12 '20 at 02:00

1 Answers1

2

If you are not sure if the input is denounced:

import { of, fromEvent } from 'rxjs'; 
import { map, tap, delay, switchMap, debounceTime } from 'rxjs/operators';

const input = document.querySelector('#search');
const fakeRequest$ = of('Requested').pipe(delay(1500))

fromEvent(input, 'keydown')
.pipe(
  tap((event) => console.log('Before debounceTime', event.target.value)),
  debounceTime(500),
  tap((event) => console.log('After debounceTime', event.target.value)),
  switchMap(() => fakeRequest$),
  tap(console.log),
)
.subscribe()

stackblitz

Lievno
  • 1,013
  • 9
  • 14