Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

160
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda