Skip to content

Instantly share code, notes, and snippets.

@Krisztiaan
Created September 29, 2019 01:39
Show Gist options
  • Save Krisztiaan/d72d1b725952d46e1236f772fe551639 to your computer and use it in GitHub Desktop.
Save Krisztiaan/d72d1b725952d46e1236f772fe551639 to your computer and use it in GitHub Desktop.
import useDebounce from "react-use/lib/useDebounce";
import { useMemo, useState, Dispatch, SetStateAction } from "react";
import Fuse, { FuseOptions } from "fuse.js";
export default <T>(
data: ReadonlyArray<T>,
fuseOptions: FuseOptions<T>,
debounce: number = 500
): [ReadonlyArray<T>, string, Dispatch<SetStateAction<string>>] => {
const [filteredData, setFilteredData] = useState(data);
const [query, setQuery] = useState("");
const fuseSearch = useMemo(() => new Fuse(data, fuseOptions), [
data,
fuseOptions
]);
useDebounce(
() => setFilteredData(query ? fuseSearch.search(query) : data),
debounce,
[query, data, debounce]
);
return [filteredData, query, setQuery];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment