Skip to content
Open
Show file tree
Hide file tree
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
100 changes: 93 additions & 7 deletions src/components/Input/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React, { useState, useMemo, useCallback, useRef } from "react";
import "./input.scss";
import { fetchData } from "../../utils/fetch-data";
import { debounce } from "../../utils/deboucne";
import Loader from "../Loader";
import { debounce } from "../../utils/debounce";

export interface InputProps {
/** Placeholder of the input */
Expand All @@ -11,13 +12,98 @@ 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>
// Your code end here
const [inputValue, setInputValue] = useState("");
const [loading, setLoading] = useState(false);
const [suggestions, setSuggestions] = useState<string[]>([]);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const latestRequestRef = useRef<number>(0);

const debouncedFetchData = useMemo(() => {
return debounce(async (query: string) => {
const requestId = Date.now();
latestRequestRef.current = requestId;
setLoading(true);
setErrorMessage(null);

try {
console.log("Fetching data for query:", query);
const data = await fetchData(query);

if (latestRequestRef.current === requestId) {
setSuggestions(data);
}
} catch (error) {
console.error("Error fetching data:", error);

if (latestRequestRef.current === requestId) {
setErrorMessage(`Error fetching data: ${error}`);
}
} finally {

if (latestRequestRef.current === requestId) {
setLoading(false);
}
}
}, 500);
}, []);

const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setInputValue(value);
if (value.trim() !== "") {
debouncedFetchData(value);
} else {
setSuggestions([]);
}
}, [debouncedFetchData]);

const handleSelectItem = useCallback((item: string) => {
onSelectItem(item);
}, [onSelectItem]);

const memoizedSuggestions = useMemo(() => {
return suggestions.length > 0 ? (
suggestions.map((item) => (
<li
key={item}
onClick={() => handleSelectItem(item)}
role="option"
tabIndex={0}
aria-selected={inputValue === item}
>
{item}
</li>
))
) : (
<li>No results found</li>
);
}, [suggestions, inputValue]);

return (
<div className="input-container">
<input
type="text"
placeholder={placeholder}
value={inputValue}
onChange={handleInputChange}
aria-label="Search input"
aria-describedby="error-message"
/>
{loading && <Loader aria-live="polite" />}
{errorMessage && (
<ul className="suggestions-list" aria-live="assertive">
<li>{errorMessage}</li>
</ul>
)}
{!loading && !errorMessage && (
<ul className="suggestions-list" role="listbox" aria-live="polite">
{memoizedSuggestions}
</ul>
)}
</div>
);
};

export default Input;

2 changes: 1 addition & 1 deletion src/utils/deboucne.ts → src/utils/debounce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ export const debounce = (callback: Function, wait: number) => {
callback(...args);
}, wait);
};
}
}
4 changes: 2 additions & 2 deletions src/utils/fetch-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export async function fetchData(query: string): Promise<string[]> {
log('fetching', query)
await delay(500 + Math.floor(Math.random() * 2000))
log('return filter for query', query)
const shouldThrow = Math.random() < 0.2
const shouldThrow = Math.random() < 0.1
if(shouldThrow) {
log('throw error for query', query)
throw `${cuteErrors[Math.floor(Math.random() * 10)]} - query: ${query}`
Expand Down Expand Up @@ -134,4 +134,4 @@ const cuteErrors = [
"Oopsie! We spilled the code everywhere 💻",
"Oh dear, the internet squirrels are on strike 🐿️",
"Well, this is awkward... let's pretend this never happened 🙈"
];
];