import React, { FunctionComponent, useCallback, useEffect, useMemo, useState, } from "react"; import { Dropdown, Form } from "react-bootstrap"; import { useHistory } from "react-router"; import { useThrottle } from "rooks"; export interface SearchResult { id: string; name: string; link?: string; } interface Props { className?: string; onSearch: (text: string) => Promise; onFocus?: () => void; onBlur?: () => void; } export const SearchBar: FunctionComponent = ({ onSearch, onFocus, onBlur, className, }) => { const [text, setText] = useState(""); const [results, setResults] = useState([]); const history = useHistory(); const search = useCallback( (value: string) => { if (value === "") { setResults([]); } else { onSearch(value).then((res) => setResults(res)); } }, [onSearch] ); const [debounceSearch] = useThrottle(search, 500); useEffect(() => { debounceSearch(text); }, [text, debounceSearch]); const clear = useCallback(() => { setText(""); setResults([]); }, []); const items = useMemo(() => { const its = results.map((v) => ( {v.name} )); if (its.length === 0) { its.push(No Found); } return its; }, [results]); return ( { if (link) { clear(); history.push(link); } }} > setText(e.currentTarget.value)} > {items} ); };