aboutsummaryrefslogtreecommitdiff
path: root/src/components/Header/SearchBar.tsx
blob: 83820285a788b2c10bfe9399a0cf6328ae823ad8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import React, { useState, useEffect } from 'react';
import SearchIcon from '@material-ui/icons/Search';
import { InputBase } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import { User } from 'which-types';
import { get } from '../../requests';


const INTERVAL = 300;

const useStyles = makeStyles(theme => ({
  root: {
    background: 'rgba(255, 255, 255, 0.5)',
    borderRadius: '2px',
    padding: theme.spacing(0.5),
    display: 'flex',
    alignItems: 'center'
  }
}));

const SearchBar: React.FC = () => {
  const classes = useStyles();
  const [query, setQuery] = useState<string>('');
  const [results, setResults] = useState<User[]>([]);
  const [isReady, setIsReady] = useState<boolean>(true);
  const [shouldRefetch, setShouldRefetch] = useState<boolean>(false);

  const sleep = () => {
    setIsReady(false);
    setTimeout(() => setIsReady(true), INTERVAL);
  };

  const fetchPolls = () => {
    sleep();
    get(`/users?username[$regex]=${query}`).then(response => {
      setResults(response.data);
    });
  }

  useEffect(() => {
    if (isReady && shouldRefetch) {
      fetchPolls();
      setShouldRefetch(false);
    }
  }, [isReady])

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
    setQuery(event.target.value);
    if (isReady) fetchPolls();
    else setShouldRefetch(true);
  };

  return (
    <div className={classes.root}>
      <SearchIcon />
      <InputBase
        placeholder="Search..."
        value={query}
        onChange={handleChange}
      />
    </div>
  );
};


export default SearchBar;