Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set input value with a debounced onChange handler

In my React Hooks app I need to let user type to an input field for 1000ms. When 1000ms expire an API request is sent with the input value.

<input type='text' name='name' className='th-input-container__input' onChange={evt => testFunc2(evt.target.value)} />

The value is set in testFunc2(evt.target.value):

const testFunc2 = useCallback(debounce((text) => setNameFilter(text), 1000), []);

Once nameFilter is set to a new value useEffect issues an API request since nameFilter is its dependency. That way the API is queried with only the resulting user input instead of with each key stroke value but the input stays uncontrolled. When I add the current nameFilter value to the input with value={nameFilter} user cannot type into the input and the input receives only the last typed character.

How do I get the user typed characters to display in the input?

like image 960
El Anonimo Avatar asked Feb 13 '26 16:02

El Anonimo


1 Answers

Updated answer:

const debouncedApiCall = useCallback(debounce((text) => {
  getRecordsForPage(1, text, '', '', '', '', 10, {});
}, 1000), [])

useEffect(() => {
  debouncedApiCall(nameFilter);
}, [nameFilter, debouncedApiCall])

<input type='text' value={nameFilter} onChange={evt => setNameFilter(evt.target.value)} />
like image 188
Loi Nguyen Huynh Avatar answered Feb 16 '26 17:02

Loi Nguyen Huynh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!