import { useCallback, useEffect, useState } from 'react'; import { useCombobox } from 'downshift'; import { Project } from 'gql-client'; import { useDebounceValue } from 'usehooks-ts'; import SearchBar from 'components/SearchBar'; import { useGQLClient } from 'context/GQLClientContext'; import { cn } from 'utils/classnames'; import { ProjectSearchBarItem } from './ProjectSearchBarItem'; import { ProjectSearchBarEmpty } from './ProjectSearchBarEmpty'; interface ProjectSearchBarProps { onChange?: (data: Project) => void; } export const ProjectSearchBar = ({ onChange }: ProjectSearchBarProps) => { const [items, setItems] = useState([]); const [selectedItem, setSelectedItem] = useState(null); const client = useGQLClient(); const { isOpen, getMenuProps, getInputProps, getItemProps, highlightedIndex, inputValue, } = useCombobox({ items, itemToString(item) { return item ? item.name : ''; }, selectedItem, onSelectedItemChange: ({ selectedItem: newSelectedItem }) => { if (newSelectedItem) { setSelectedItem(newSelectedItem); if (onChange) { onChange(newSelectedItem); } } }, }); const [debouncedInputValue, _] = useDebounceValue(inputValue, 300); const fetchProjects = useCallback( async (inputValue: string) => { const { searchProjects } = await client.searchProjects(inputValue); setItems(searchProjects); }, [client], ); useEffect(() => { if (debouncedInputValue) { fetchProjects(debouncedInputValue); } }, [fetchProjects, debouncedInputValue]); return (
{items.length ? ( <>

Suggestions

{items.map((item, index) => ( ))} ) : ( )}
); };