diff --git a/src/components/Input/index.tsx b/src/components/Input/index.tsx index 453c742..37e0744 100644 --- a/src/components/Input/index.tsx +++ b/src/components/Input/index.tsx @@ -1,4 +1,5 @@ import "./input.scss"; +import { useCallback, useState, useEffect } from "react"; import { fetchData } from "../../utils/fetch-data"; import { debounce } from "../../utils/deboucne"; import Loader from "../Loader"; @@ -15,7 +16,72 @@ const Input = ({ placeholder, onSelectItem }: InputProps) => { console.log('input re-render') // Your code start here - return + const [initital, setInitital] = useState(true); + const [fetching, setFetching] = useState(false); + const [query, setQuery] = useState(null); + const [error, setError] = useState(""); + const [listResults, setListResults] = useState([]); + + useEffect(() => { + let isMounted = true; + if(query != null) { + setInitital(false); + setFetching(true); + fetchData(query) + .then(resp => { + if(isMounted) { + setError(""); + setFetching(false); + console.log(resp); + setListResults(resp); + } + }) + .catch ((err) => { + setError(err as string); + setFetching(false); + }) + } + return () => { + isMounted = false; // Prevent state updates on unmounted component + }; + }, [query]); + + const onInputSearch = useCallback(debounce((query: any) => { + setQuery(query); + }, 100), []) + + const renderHTML = () => { + if(fetching) { + return + } else if(error) { + return

{error}

+ } else { + const htmlResult = listResults.length ? + : +
No Results
; + return htmlResult; + } + } + + return ( + <> + onInputSearch((evt.target as HTMLTextAreaElement).value)}> +
+ {!initital ? renderHTML(): ""} +
+ + ); // Your code end here }; diff --git a/src/components/Input/input.scss b/src/components/Input/input.scss index 1dafbe7..2a96654 100644 --- a/src/components/Input/input.scss +++ b/src/components/Input/input.scss @@ -4,3 +4,30 @@ html{ font-size: 16px; } + +input { + font-size: 16px; + padding: 8px; + border: 1px solid grey; + border-radius: 10px; +} + +.text-error { + color: red; +} + +.search-result { + margin-top: 16px; +} + +.result-list { + text-align: left; + padding-left: 0; + list-style: none; + + li { + &:hover { + cursor: pointer; + } + } +}