import { useEffect, useRef, useState } from 'react' import { api } from '../utils/api' export default function FoodSearchModal({ title, initialQuery, onSelect, onClose }) { const [q, setQ] = useState(initialQuery || '') const [hits, setHits] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useState(null) const inputRef = useRef(null) const timer = useRef(null) const runSearch = async (term) => { const query = (term || '').trim() if (query.length < 2) { setHits([]) return } setLoading(true) setError(null) try { setHits(await api.searchBlsFoods(query, 30)) } catch (e) { setError(e.message) setHits([]) } finally { setLoading(false) } } useEffect(() => { inputRef.current?.focus() inputRef.current?.select() if ((initialQuery || '').trim().length >= 2) runSearch(initialQuery) const onKey = (e) => { if (e.key === 'Escape') onClose() } window.addEventListener('keydown', onKey) return () => { window.removeEventListener('keydown', onKey) clearTimeout(timer.current) } }, []) const onChange = (value) => { setQ(value) clearTimeout(timer.current) timer.current = setTimeout(() => runSearch(value), 250) } return (
Suche nach dem Namen. Den BLS-Code brauchst du nicht.
Suche…
} {error &&{error}
} {!loading && q.trim().length >= 2 && hits.length === 0 && (Kein Treffer. Anderen Suchbegriff versuchen.
)} {hits.map((h) => ( ))}