-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathuseDebounceHook.ts
More file actions
66 lines (56 loc) · 1.75 KB
/
useDebounceHook.ts
File metadata and controls
66 lines (56 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { useEffect, useRef, useState } from "react";
import { TypeaheadOptions } from "../types/Typeahead";
interface DebounceSearch {
query: string;
delay: number;
}
const useDebounceHook = (queryFn: (query: string) => Promise<TypeaheadOptions>, setOptions: (results: TypeaheadOptions) => void) => {
const queryRef = useRef("");
const [isLoading, setIsLoading] = useState(false);
const [debounceSearch, setDebounceSearch] = useState<DebounceSearch | undefined>();
useEffect(() => {
if (debounceSearch) {
const { delay: counter, query } = debounceSearch;
queryRef.current = query;
const timer =
counter > 0
? setTimeout(
() =>
setDebounceSearch((prev) => ({
...(prev as DebounceSearch),
delay: (prev as DebounceSearch)?.delay - 100,
})),
100,
)
: undefined;
if (counter === 0) {
void (async () => {
try {
const results = await queryFn(query);
if (queryRef.current === query) {
if (queryRef.current === "") {
setOptions([]);
} else {
setOptions(results);
}
setIsLoading(false);
}
} catch {
setIsLoading(false);
}
})();
// eslint-disable-next-line react-hooks/set-state-in-effect
setDebounceSearch(undefined);
} else {
setIsLoading(true);
}
return () => {
clearTimeout(timer);
};
}
// not all paths returns a value
return;
}, [queryFn, setOptions, debounceSearch]);
return { setDebounceSearch, isLoading, queryRef };
};
export { useDebounceHook };