Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!