Created
September 29, 2019 01:39
-
-
Save Krisztiaan/d72d1b725952d46e1236f772fe551639 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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