ThePainnn
ThePainnn

Reputation: 441

RXJS debounce ajax calls

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!

Upvotes: 1

Views: 480

Answers (1)

Lievno
Lievno

Reputation: 1041

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

Upvotes: 2

Related Questions