From fa65b15a18a30060d4d6d663c8b2391d44e3fa63 Mon Sep 17 00:00:00 2001
From: eug-vs <eug-vs@keemail.me>
Date: Sun, 28 Jun 2020 02:25:01 +0300
Subject: feat: implement searchBar fetching logic

---
 src/components/Header/SearchBar.tsx | 38 ++++++++++++++++++++++++++++++++++++-
 1 file changed, 37 insertions(+), 1 deletion(-)

(limited to 'src/components/Header/SearchBar.tsx')

diff --git a/src/components/Header/SearchBar.tsx b/src/components/Header/SearchBar.tsx
index 182a1a4..8382028 100644
--- a/src/components/Header/SearchBar.tsx
+++ b/src/components/Header/SearchBar.tsx
@@ -1,7 +1,12 @@
-import React from 'react';
+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: {
@@ -15,12 +20,43 @@ const useStyles = makeStyles(theme => ({
 
 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>
   );
-- 
cgit v1.2.3

