Untitled
unknown
plain_text
a year ago
1.4 kB
12
Indexable
import { h } from 'preact';
import { useState, useEffect } from 'preact/hooks';
const SearchBox = ({ fetchResults }) => {
const [searchTerm, setSearchTerm] = useState('');
const [results, setResults] = useState([]);
const [isTyping, setIsTyping] = useState(false);
let timeoutId;
const handleInputChange = (e) => {
setSearchTerm(e.target.value);
setIsTyping(true);
// Clear the previous timeout
if (timeoutId) clearTimeout(timeoutId);
// Set a new timeout
timeoutId = setTimeout(() => {
// Call the search function
fetchResults(e.target.value).then(res => {
setResults(res);
setIsTyping(false);
});
}, 500); // Debounce delay of 500ms
};
return (
<div>
<input
type="text"
value={searchTerm}
onChange={handleInputChange} // or use onInput for more immediate feedback
placeholder="Search..."
/>
{isTyping && <div>Typing...</div>} {/* Show typing indicator */}
{results.length > 0 && !isTyping && ( /* Hide results if still typing */
<ul>
{results.map((result, index) => (
<li key={index}>{result}</li>
))}
</ul>
)}
</div>
);
};
export default SearchBox;Editor is loading...
Leave a Comment