Set input value with a debounced onChange handler

夙愿已清 提交于 2019-12-24 17:12:12

问题


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?


回答1:


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)} />


来源:https://stackoverflow.com/questions/59358092/set-input-value-with-a-debounced-onchange-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!