Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
Problema de representación del componente de búsqueda con validar js

Tengo componente de búsqueda con validar js.

Problema: cuando mi entrada en foucs por primera vez, la validación y la solicitud no funcionan, pero cuando pierdo el foco de mi entrada, hago clic nuevamente e intente nuevamente, la búsqueda funciona sin validación

 interface IProps { onSearchChange?: (event: React.ChangeEvent<HTMLInputElement>) => void; } const Search: React.FC<IProps> = ({ onSearchChange }) => { const inputRef = useRef<HTMLInputElement>(null); const [inputIsTouched, setInputIsTouched] = useState(false); const currentValue = inputRef.current?.value && inputRef.current.value; const validateErrors = validate({ currentValue }, constraints); const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { if (validateErrors?.currentValue) { return; } currentValue && onSearchChange && onSearchChange(event); setInputIsTouched(true); }; const debouncedOnChange = debounce(handleChange, 1000); return ( <div className={classes['Root']}> <Input type="text" autoComplete="off" placeholder="..." onChange={debouncedOnChange} ref={inputRef} onBlur={() => setInputIsTouched(true)} isError={inputIsTouched && !!validateErrors?.currentValue} /> <div className={classes['ErrorContainer']}> {inputIsTouched && validateErrors?.currentValue && ( <Text color="error" size="s"> {validateErrors.currentValue} </Text> )} </div> </div> ); };
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Eso es de esperar porque en el primer procesamiento, currentValue no está undefined (ya que inputRef.current es null ) y no hay nada que llame a handleChange para activar la búsqueda.

Debe asegurarse de que la lógica handleChange también se ejecute en el renderizado inicial, por lo que debería verse así:

 const Search: React.FC<IProps> = ({ onSearchChange }) => { // Use a single object for all input state props: const [{ isTouched, validateErrors, }, setInputState] = useState({ isTouched: false, validateErrors: null, }); const inputRef = useRef<HTMLInputElement>(null); // Debounce only search callback: const debouncedSearchChange = debounce(onSearchChange, 1000); const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => { // Get the current value: const currentValue = e.currentTarget.value; // Validate it: const validateErrors = validate({ currentValue }, constraints); if (validateErrors?.currentValue) { // And handle error: setInputState(prevState => ({ ...prevState, validateErrors })); return; } // Or success: setInputState(prevState => ({ ...prevState, validateErrors: null })); // And trigger the debounced search if needed: if (currentValue && debouncedSearchChange ) debouncedSearchChange(event); }, [constraints, debouncedSearchChange]); // Trigger validation and search on first render: useEffect(() => { const inputElement = inputRef.current; // TypeScript will complain about this line, so you might want to // re-structure the logic above to accommodate this: if (inputElement) handleChange({ currentTarget: inputElement }); }, []); return ( <div className={classes['Root']}> <Input type="text" autoComplete="off" placeholder="..." onChange={handleChange} ref={inputRef} onBlur={() => setInputState(prevState => ({ ...prevState, isTouched: true }))} isError={inputIsTouched && !!validateErrors?.currentValue} /> <div className={classes['ErrorContainer']}> {inputIsTouched && validateErrors?.currentValue && ( <Text color="error" size="s"> {validateErrors.currentValue} </Text> )} </div> </div> ); };
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda