Last active
April 1, 2021 13:57
-
-
Save Krisztiaan/72341dca172c1ef2eea1aec626e95ff3 to your computer and use it in GitHub Desktop.
Simple hook to use Fuse.js
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
{ | |
"name": "use-fuse", | |
"version": "1.0.1", | |
"main": "useFuse.ts" | |
} |
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 { useCallback, useMemo, useState } from "react"; | |
import Fuse from "fuse.js"; | |
export default function useFuse<T>( | |
list: ReadonlyArray<T>, | |
fuseOptions?: Fuse.IFuseOptions<T>, | |
index?: Fuse.FuseIndex<T> | |
): [filteredData: ReadonlyArray<T>, search: (query: string) => void] { | |
const [filteredData, setFilteredData] = useState(list); | |
const fuseSearch = useMemo(() => new Fuse(list, fuseOptions, index), [ | |
list, | |
fuseOptions, | |
]); | |
const search = useCallback( | |
(query: string) => | |
setFilteredData(fuseSearch.search(query).map((i) => i.item)), | |
[fuseSearch] | |
); | |
return [filteredData, search]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment