Answers for "react rxjs autocomplete"

1

react rxjs autocomplete

import { BehaviorSubject } from 'rxjs';
import { ajax, AjaxResponse } from 'rxjs/ajax';
import { map, filter, switchMap, debounceTime } from 'rxjs/operators';

const getApiUrl = (value: string) => `/response.json?value=${value}`;

const transformResponse = ({ response }: AjaxResponse) => {
  return response.bestMatches.map(item => ({
    symbol: item['1. symbol'],
    name: item['2. name'],
    type: item['3. type'],
    region: item['4. region'],
    marketOpen: item['5. marketOpen'],
    marketClose: item['6. marketClose'],
    timezone: item['7. timezone'],
    currency: item['8. currency'],
    matchScore: item['9. matchScore']
  }));
};

export const getSuggestions = (subject: BehaviorSubject<string>) => {
  return subject.pipe(
    debounceTime(500), // wait until user stops typing
    filter(v => v.length > 2), // send request only if there are 3 or more characters
    map(getApiUrl), // form url for the API call
    switchMap(url => ajax(url)), // call HTTP endpoint and cancel previous requests
    map(transformResponse) // change response shape for autocomplete consumption
  );
};
Posted by: Guest on July-06-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language