-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuzzy.hooks.ts
47 lines (39 loc) · 938 Bytes
/
fuzzy.hooks.ts
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
import React from "react";
import Fuse from "fuse.js";
import { debounce } from "debounce";
export const useFuzzySearch = <T>(
data: readonly T[],
opts?: Fuse.IFuseOptions<T>
) => {
const [results, setResults] = React.useState<Fuse.FuseResult<T>[]>();
let fuse: Fuse<T>;
if (!opts) {
fuse = new Fuse(data, {
includeScore: true,
includeMatches: true,
});
} else {
fuse = new Fuse(data, opts);
}
const _search = React.useCallback(
(text: string) => {
const results: Fuse.FuseResult<T>[] = fuse.search(`=${text}`, {
limit: 20,
});
setResults(results);
},
[data]
);
const search = React.useCallback(debounce(_search, 200), [data]);
React.useEffect(() => {
// console.log("useFuzzySearch mounted.");
return () => {
// console.log("useFuzzySearch unmounted.");
};
}, []);
return {
results,
setResults,
search,
};
};