diff --git a/src/components/Input/index.tsx b/src/components/Input/index.tsx index 453c742..1dc8f74 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 { ChangeEvent, useCallback, useState } from "react"; export interface InputProps { /** Placeholder of the input */ @@ -14,8 +15,61 @@ const Input = ({ placeholder, onSelectItem }: InputProps) => { // DO NOT remove this log console.log('input re-render') + const [result, setResult] = useState([]); + + const [text, setText] = useState('') + + const [state, setState] = useState('success'); + + const onFetch = debounce(async (input: string) => { + try { + if (!input) { + setResult([]); + return; + } + setState('loading'); + const response = await fetchData(input); + setResult(response); + setState('success'); + } catch (err) { + setState('error'); + console.log("Err", err); + } + }, 1000) + + const handleFetchData = useCallback(async (event: ChangeEvent) => { + setText(event.target.value); + onFetch(event.target.value); + }, []) + + const handleSelectItem = useCallback((item: string) => { + setText(item); + onSelectItem(item) + setResult([]); + }, []) + // Your code start here - return + return ( +
+ + { + state === 'loading' && ( + + ) + } + { + state === 'success' && + result && result.length > 0 && + result.map((item, index) => { + return ( +
handleSelectItem(item)}> + {item} +
+ ) + }) + } +
+ ) // Your code end here };