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
Sounds you are going to need to use setTimeout
to start a timer as soon as the user enters text. If the user enters another character, restart the timer. If the user does not type again before the timer completes, it will fire an action that toggles the checkbox:
class App extends React.Component {
constructor() {
super();
this.state = {
text: '',
checked: false
};
this.timer = null;
}
componentDidUpdate (prevProps, prevState) {
if(prevState.text !== this.state.text) {
this.handleCheck();
}
}
onChange = e => {
this.setState({
text: e.target.value
});
};
handleCheck = () => {
// Clears running timer and starts a new one each time the user types
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.toggleCheck();
}, 1000);
}
toggleCheck = () => {
this.setState( prevState => ({ checked: !prevState.checked }));
}
render () {
return (
)
}
}
ReactDOM.render( , document.getElementById('root'));