I need to use debounce
on input onChange
, but I also need the value from the form's initialValues
. On adding debounce with value={props.value}
nothing happens in the textbox on typing which is expected as props.value
get updated after the debounce timer. But what is the solution for this?
const debounced = debounce(e => {
input.onChange(e);
}, 500);
<FormControl
value={input.value}
onChange={e => {
e.persist();
debounced(e);
}}
/>
In the above case, nothing gets typed in the input box. And if I don't pass value
prop, I don't get my existing value auto-populated in the input box.
Would love to get suggestions on how to achieve this.
Thanks in advance!
The following should debounce the input and update the state accordingly.
const { useState } = React; const debounce = (callback, wait) => { let timeoutId = null; return (...args) => { window.clearTimeout(timeoutId); timeoutId = window.setTimeout(() => { callback.apply(null, args); }, wait); }; } const App = () => { const [current, setCurrent] = useState(''); const handleChange = debounce(e => setCurrent(e.target.value), 500); return ( <div> <form> <input type="text" onChange={handleChange} /> <p>{current}</p> </form> </div> ); }; ReactDOM.render(<App />, document.getElementById('react'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <div id="react"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.