66 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
		
		
			
		
	
	
			66 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
|  | import React, { useState, useEffect } from 'react'; | ||
|  | 
 | ||
|  | interface AutocompleteInputProps { | ||
|  |   value: string; | ||
|  |   onChange: (e: React.ChangeEvent<HTMLInputElement>) => void; | ||
|  |   name: string; | ||
|  |   placeholder?: string; | ||
|  |   // CAMBIO: La función ahora recibe el término de búsqueda
 | ||
|  |   fetchSuggestions: (query: string) => Promise<string[]>; | ||
|  |   className?: string; | ||
|  | } | ||
|  | 
 | ||
|  | const AutocompleteInput: React.FC<AutocompleteInputProps> = ({ | ||
|  |   value, | ||
|  |   onChange, | ||
|  |   name, | ||
|  |   placeholder, | ||
|  |   fetchSuggestions, | ||
|  |   className | ||
|  | }) => { | ||
|  |   const [suggestions, setSuggestions] = useState<string[]>([]); | ||
|  |   const dataListId = `suggestions-for-${name}`; | ||
|  | 
 | ||
|  |   // CAMBIO: Lógica de "debouncing" para buscar mientras se escribe
 | ||
|  |   useEffect(() => { | ||
|  |     // No buscar si el input está vacío o es muy corto
 | ||
|  |     if (value.length < 2) { | ||
|  |       setSuggestions([]); | ||
|  |       return; | ||
|  |     } | ||
|  | 
 | ||
|  |     // Configura un temporizador para esperar 300ms después de la última pulsación
 | ||
|  |     const handler = setTimeout(() => { | ||
|  |       fetchSuggestions(value) | ||
|  |         .then(setSuggestions) | ||
|  |         .catch(err => console.error(`Error fetching suggestions for ${name}:`, err)); | ||
|  |     }, 300); | ||
|  | 
 | ||
|  |     // Limpia el temporizador si el usuario sigue escribiendo
 | ||
|  |     return () => { | ||
|  |       clearTimeout(handler); | ||
|  |     }; | ||
|  |   }, [value, fetchSuggestions, name]); | ||
|  | 
 | ||
|  |   return ( | ||
|  |     <> | ||
|  |       <input | ||
|  |         type="text" | ||
|  |         name={name} | ||
|  |         value={value} | ||
|  |         onChange={onChange} | ||
|  |         placeholder={placeholder} | ||
|  |         className={className} | ||
|  |         list={dataListId} | ||
|  |         autoComplete="off" // Importante para que no interfiera el autocompletado del navegador
 | ||
|  |       /> | ||
|  |       <datalist id={dataListId}> | ||
|  |         {suggestions.map((suggestion, index) => ( | ||
|  |           <option key={index} value={suggestion} /> | ||
|  |         ))} | ||
|  |       </datalist> | ||
|  |     </> | ||
|  |   ); | ||
|  | }; | ||
|  | 
 | ||
|  | export default AutocompleteInput; |