debounce-search-abstraction
A tool to easily make the search debounce properly
ℹ️ it doesn't interact with DOM. It's abstract. You feed it with a search query, and it invokes your data callbacks.
It encapsulates debounce for your queries and skips the late results (concurrent requests).
Usage
npm i debounce-search-abstraction
import { DebounceSearch } from 'debounce-search-abstraction';
type SearchResult = {
transformedQuery: string;
};
const search = new DebounceSearch<SearchResult>({
debounceMs: 300,
async resultsProvider({ query, setResults, isQueryStillActual }) {
requestCallback(query);
await sleep(200);
const upperCased = query.toUpperCase();
setResults({
transformedQuery: upperCased,
});
if (isQueryStillActual()) {
await sleep(200);
setResults({
transformedQuery: `${upperCased} (${upperCased.length})`,
});
}
},
resultsProcessor(result) {
resultsProcessorCallback(result.transformedQuery);
},
emptyQueryResult: () => ({
transformedQuery: '',
}),
});
const scenario: Array<
[string, number, null | string, string[] | null]
> = [
['H', 300, 'H', null],
['e', 400, 'He', null],
['l', 200, null, null],
['l', 601, 'Hell', ['HELL']],
['o', 1001, 'Hello', ['HELLO', 'HELLO (5)']],
[' ', 250, null, null],
['T', 600, 'Hello T', ['HELLO T']],
['h', 300, 'Hello Th', null],
['e', 100, null, null],
['r', 200, null, null],
['e', 400, 'Hello There', null],
['!', 800, 'Hello There!', ['HELLO THERE!', 'HELLO THERE! (12)']],
['', 800, '', ['', ' (0)']],
];