Skip to content

Instantly share code, notes, and snippets.

@Krisztiaan
Last active April 1, 2021 13:57
Show Gist options
  • Save Krisztiaan/72341dca172c1ef2eea1aec626e95ff3 to your computer and use it in GitHub Desktop.
Save Krisztiaan/72341dca172c1ef2eea1aec626e95ff3 to your computer and use it in GitHub Desktop.
Simple hook to use Fuse.js
{
"name": "use-fuse",
"version": "1.0.1",
"main": "useFuse.ts"
}
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