Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 94 additions & 4 deletions src/components/Input/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand All @@ -12,12 +13,101 @@ 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 <input></input>
const [inputValue, setInputValue] = useState("");
const [status, setStatus] = useState<
"initial" | "fetching" | "success" | "error"
>("initial");
const [items, setItems] = useState<string[]>([]);
const [errorMessage, setErrorMessage] = useState("");

useEffect(() => {
let isCurrent = true;

const handleFetchData = async (value: string) => {
if (!value) {
setStatus("initial");
setItems([]);
setErrorMessage("");
return;
}

setStatus("fetching");
setErrorMessage("");

try {
const result = await fetchData(value);
if (isCurrent) {
setItems(result.length ? result : []);
setStatus("success");
}
} catch (error) {
if (isCurrent) {
setStatus("error");
setErrorMessage(error as string);
}
}
};

// Debounced version of handleFetchData test deploy
const debouncedFetchData = debounce(handleFetchData, 100);

if (inputValue) {
debouncedFetchData(inputValue);
}

return () => {
isCurrent = false;
};
}, [inputValue]);

// Handle input change
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
};

// Handle item click
const handleItemClick = (item: string) => {
onSelectItem(item);
};

return (
<div className="input-container">
{/* Input */}
<input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder={placeholder}
className="input-field"
/>

{/* Loader */}
{status === "fetching" && <Loader />}

{/* Error message */}
{status === "error" && errorMessage && (
<p className="error-message">{errorMessage}</p>
)}

{/* List of items */}
{status === "success" && (
<ul className="item-list">
{items.length ? (
items.map((item, index) => (
<li key={index} onClick={() => handleItemClick(item)}>
{item}
</li>
))
) : (
<p>No results</p>
)}
</ul>
)}
</div>
);
// Your code end here
};

export default Input;