diff --git a/src/components/Input/index.tsx b/src/components/Input/index.tsx index 453c742..c3e5142 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 */ @@ -14,9 +15,70 @@ const Input = ({ placeholder, onSelectItem }: InputProps) => { // DO NOT remove this log console.log('input re-render') - // Your code start here - return - // Your code end here + const [inputValue, setInputValue] = useState(''); + const [status, setStatus] = useState('initial'); + const [items, setItems] = useState([]); + const [error, setError] = useState(''); + + const handleInputChange = (value: string) => { + setInputValue(value); + if (value.trim() === '') { + setStatus('initial'); + setItems([]); + setError(''); + } else { + setStatus('fetching'); + } + }; + + const debouncedChangeHandler = debounce(handleInputChange, 100); + + const onTyping = (e: React.ChangeEvent) => { + debouncedChangeHandler(e.target.value); + }; + + const handleSelectedItem = (item: string) => { + console.log("selected item ==>", item); + onSelectItem(item); + }; + + useEffect(() => { + if (status === 'fetching' && inputValue !== '') { + fetchData(inputValue) + .then(result => { + setItems(result); + setStatus(result.length === 0 ? 'success' : 'success'); + }) + .catch(err => { + console.error(err); + setError('Error fetching data. Please try again later.'); + setStatus('error'); + }); + } + }, [inputValue]); + + return ( +
+ + {status === 'fetching' && } + {status === 'success' && ( + items.length > 0 ? ( +
    + {items.map((item, index) => ( +
  • handleSelectedItem(item)}>{item}
  • + ))} +
+ ) :
No results
+ )} + {status === 'error' &&
{error}
} +
+ ); }; export default Input; diff --git a/src/components/Input/input.scss b/src/components/Input/input.scss index 1dafbe7..b6efbea 100644 --- a/src/components/Input/input.scss +++ b/src/components/Input/input.scss @@ -4,3 +4,36 @@ html{ font-size: 16px; } + +.form-control { + display: block; + width: 100%; + padding: .375rem .75rem; + font-size: 1rem; + font-weight: 400; + line-height: 1.5; + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; + background-clip: padding-box; + border: 1px solid #dee2e6; + border-radius: 0.375rem; + transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out; +} + +.list-component { + ul { + list-style: none; + padding: 0; + + li { + cursor: pointer; + padding: 8px 16px; + border-bottom: 1px solid #ccc; + + &:hover { + background-color: #f8f9fa; + } + } + } + } \ No newline at end of file