diff --git a/src/components/Input/index.tsx b/src/components/Input/index.tsx index 453c742..aad9ecd 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 { useRef, useState } from "react"; export interface InputProps { /** Placeholder of the input */ @@ -9,13 +10,63 @@ export interface InputProps { /** On click item handler */ onSelectItem: (item: string) => void; } - +export enum InputState { + INITITAL = 'initital', + FETCHING = 'fetching', + SUCCESS = 'success', + ERROR = 'error', +} const Input = ({ placeholder, onSelectItem }: InputProps) => { // DO NOT remove this log console.log('input re-render') // Your code start here - return + const [status, setStatus] = useState(InputState.INITITAL); + const [data, setData] = useState(); + const [error, setError] = useState(''); + + const lastTimeID = useRef(0); + + const handleChange = debounce(async (event: React.ChangeEvent) => { + const query = event.target.value; + if(!query) { + setStatus(InputState.INITITAL); + setData([]); + setError(''); + lastTimeID.current = 0; + return; + } + const currentTime = new Date().getTime(); + lastTimeID.current = currentTime; + try { + if(status !== InputState.FETCHING) { + setStatus(InputState.FETCHING); + } + const response = await fetchData(query); + + if(lastTimeID.current !== currentTime) return; + + setData(response); + setStatus(InputState.SUCCESS); + + } catch (error) { + if(lastTimeID.current !== currentTime) return; + + setStatus(InputState.ERROR); + setError(error as string) + } + }, 100) + + return + + {status !== InputState.INITITAL && + {status === InputState.FETCHING && } + {status === InputState.ERROR && {error}} + {status === InputState.SUCCESS && + {!!data?.length ? data.map((item, index) => onSelectItem(item)}>{item}) : 'No results'} + } + } + // Your code end here }; diff --git a/src/components/Input/input.scss b/src/components/Input/input.scss index 1dafbe7..92e905f 100644 --- a/src/components/Input/input.scss +++ b/src/components/Input/input.scss @@ -4,3 +4,39 @@ html{ font-size: 16px; } +.search-container { + width: 320px; + &__input { + width: 100%; + font-size: 16px; + padding: 12px; + border-radius: 4px; + border: 1px solid #2d3436; + } + &__content { + margin-top: 8px; + position: relative; + border: 1px solid #dfe6e9; + border-radius: 4px; + min-height: 80px; + text-align: left; + } + &__result { + display: flex; + flex-direction: column; + gap: 8px; + justify-content: center; + } + &__error { + color: #d63031; + } + &__item { + cursor: pointer; + padding: 12px; + &:hover { + background: #34495e; + color: white; + } + } + +}