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

154
Visualizações
Search component render problem with validate js

I have search component with validate js.

Problem: when my input in foucs first time, validate and request dont work, but when i lose focus my input, and click it again, and try again, search working without validation

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

That's expected because on first render, currentValue is undefined (as inputRef.current is null) and there's nothing calling handleChange to trigger the search.

You need to make sure the handleChange logic also runs on the initial render, so it should look something like this:

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