import React, { useCallback, useEffect, useState } from 'react'; import { useCombobox } from 'downshift'; import { Project } from 'gql-client'; import { useDebounce } from 'usehooks-ts'; import { List, ListItem, ListItemPrefix, Card, Typography, Avatar, } from '@material-tailwind/react'; import SearchBar from '../SearchBar'; import { useGQLClient } from '../../context/GQLClientContext'; interface ProjectsSearchProps { onChange?: (data: Project) => void; } const ProjectSearchBar = ({ onChange }: ProjectsSearchProps) => { 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 = useDebounce(inputValue, 500); 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) => (
{item.name} {item.organization.name}
))} ) : (
^ No projects matching this name
)}
); }; export default ProjectSearchBar;