diff --git a/src/components/Input/index.tsx b/src/components/Input/index.tsx
index 453c742..4aeb0e3 100644
--- a/src/components/Input/index.tsx
+++ b/src/components/Input/index.tsx
@@ -2,6 +2,7 @@ import "./input.scss";
import { fetchData } from "../../utils/fetch-data";
import { debounce } from "../../utils/deboucne";
import Loader from "../Loader";
+import { useEffect, useState } from "react";
export interface InputProps {
/** Placeholder of the input */
@@ -12,12 +13,82 @@ export interface InputProps {
const Input = ({ placeholder, onSelectItem }: InputProps) => {
// DO NOT remove this log
- console.log('input re-render')
+ console.log("input re-render");
// Your code start here
- return
+ const [result, setResult] = useState([]);
+ const [errorMessage, setErrorMessage] = useState("");
+
+ const [searchString, setSearchString] = useState("");
+ const [isLoading, setIsLoading] = useState(false);
+ const [isEmptySearch, setIsEmptySearch] = useState(true);
+
+ const handleInputChange = debounce((value: string) => {
+ if (!value) {
+ setIsEmptySearch(true);
+ setErrorMessage("");
+ setSearchString("");
+ return;
+ }
+ setIsLoading(true);
+ setSearchString(value);
+ }, 100);
+
+ useEffect(() => {
+ if (!searchString) return;
+ let skip = false;
+ fetchData(searchString)
+ .then((data) => {
+ if (skip) return;
+ setErrorMessage("");
+ setResult(data);
+ setIsEmptySearch(false);
+ })
+ .catch((error) => {
+ if (skip) return;
+ setErrorMessage(error);
+ setIsEmptySearch(false);
+ setResult([]);
+ })
+ .finally(() => {
+ setIsLoading(false);
+ });
+
+ return () => {
+ skip = true;
+ };
+ }, [searchString]);
+
+ const resultRender = () => {
+ if (isLoading) return ;
+
+ if (errorMessage) return {errorMessage}
;
+
+ if (result && result.length) {
+ return (
+
+ {result.map((item, index) => (
+ - onSelectItem(item)}>
+ {item}
+
+ ))}
+
+ );
+ }
+
+ if (result && !result.length) return No item found!
;
+ };
+
+ return (
+ <>
+ handleInputChange(e.target.value)}
+ >
+ {!isEmptySearch && resultRender()}
+ >
+ );
// Your code end here
};
export default Input;
-