import React, { useState, useEffect, useCallback } from 'react'; import SearchIcon from '@material-ui/icons/Search'; import { InputBase, List, ListItem, Paper, Divider, ClickAwayListener } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; import { User } from 'which-types'; import { get } from '../../requests'; import UserStrip from '../UserStrip/UserStrip'; interface PropTypes { navigate: (prefix: string, id: string) => void; } const INTERVAL = 300; const LIMIT = 7; const useStyles = makeStyles(theme => ({ root: { position: 'relative', background: 'rgba(255, 255, 255, 0.5)', borderRadius: '2px', padding: theme.spacing(0.5), display: 'flex', alignItems: 'center' }, results: { position: 'absolute', width: '100%', top: theme.spacing(5) } })); const SearchBar: React.FC = ({ navigate }) => { const [query, setQuery] = useState(''); const [results, setResults] = useState([]); const [isReady, setIsReady] = useState(true); const [shouldRefetch, setShouldRefetch] = useState(false); const classes = useStyles(); const sleep = () => { setIsReady(false); setTimeout(() => setIsReady(true), INTERVAL); }; const fetchPolls = useCallback(() => { sleep(); get(`/users?username[$regex]=${query}&$limit=${LIMIT}`).then(response => { setResults(response.data); }); }, [query]); useEffect(() => { if (isReady && shouldRefetch) { fetchPolls(); setShouldRefetch(false); } }, [isReady, fetchPolls, shouldRefetch]); const handleChange = (event: React.ChangeEvent): void => { setQuery(event.target.value); if (isReady) fetchPolls(); else setShouldRefetch(true); }; const handleClose = () => { setQuery(''); setResults([]); }; const handleNavigate = (index: number) => () => { navigate('profile', results[index]._id); handleClose(); }; const SearchResults = ( { results.map((result, index) => ( <> {(index < results.length - 1) && } )) } ); return (
{results.length > 0 && SearchResults}
); }; export default SearchBar;