I need the state to change to maintain the string the user is typing. However I want to delay an action until the user stops typing. But I can\'t quite place my finger on how to
One way to do this would be to have your onChange
handler execute two functions:
Example code:
import debounce from 'lodash.debounce';
class Foo extends React.Component {
constructor() {
super()
this.state = {
value: ''
}
// Delay action 2 seconds
this.onChangeDebounced = debounce(this.onChangeDebounced, 2000)
}
handleInputChange = (e: Event) => {
// Immediately update the state
this.setState({
value: e.target.value
})
// Execute the debounced onChange method
this.onChangeDebounced(e)
}
onChangeDebounced = (e: Event) => {
// Delayed logic goes here
}
render() {
return (
)
}
}