I am attempting to throttle this input field. The reason is because I want to save the input value into redux state and I read that you should not use redux state with onChange handlers because redux is not meant for high frequency state changes as opposed to local state. I tried the following but because it is a controlled input where the value is equal to the state the value is not updating.
class Information extends Component {
state = {
myvalue:''
}
changeHandler = (e) =>{
setTimeout(()=>{
this.setState({
myvalue:e.target.value
})
},1000)
}
render() {
return (<div>
<textarea value={this.state.myvalue} onChange={this.changeHandler} />
</div>);
}
}
export default Information;
You probably don't want to delay setting the local state, because that will still cause the redux state update to happen at the same frequency. Your issue with the code provided is that the value isn't being updated because of setTimeout. You need to keep the input up-to-date in real time.
Instead, update the local state value in sync, and update the redux value with the setTimeout.
You'll need to set a variable for the timeout id, so you can remove it before setting another timeout. Once no changes have been made for the duration of the timeout, then the timeout will resolve, and the redux state can be updated.
constructor() {
// set a property to name your timeout
this.reduxTimer = null
}
changeHandler = (e) => {
// clear an existing timeout
clearTimeout(this.reduxTimer)
// set your component state
this.setState({ myvalue: e.target.value })
// reset the timeout and assign its ID to the variable
this.reduxTimer = setTimeout(() => {
// set redux state
}, 1000)
}