UNPKG

ohmysearch

Version:

Ohmysearch - customizable all in one search tool to boost developer productivity

41 lines (34 loc) 1.02 kB
import { useCallback, useMemo, useRef, useState } from "react"; import Fuse from "fuse.js"; import { useStore } from "../stores/global-stores"; export function useFuse<T>( docs: T[], options: Fuse.IFuseOptions<T> & { matchAllOnEmptyQuery?: boolean; limit?: number; } ) { const [query, updateQuery] = useState(""); const globalInstanceCount = useRef(0); const { limit, matchAllOnEmptyQuery, ...fuseOptions } = options; const fuse = useMemo(() => { globalInstanceCount.current++; return new Fuse<T>(docs, options); }, [docs, options]); const hits: Fuse.FuseResult<T>[] = useMemo(() => { const data = !query && matchAllOnEmptyQuery ? docs.map((item, refIndex) => ({ item, refIndex })) : fuse.search(query, { limit: limit || 1000 }); return data; }, [fuse, limit, matchAllOnEmptyQuery, query]); console.info( "[use-fuzzy-search] Total Fuse Index count", globalInstanceCount.current ); return { hits, query, updateQuery, }; }