I don\'t want to fire requests as long as the user is typing. My code should throttle requests so that when the user types quickly, it will fire one request with the latest inpu
Well this is easy with lodash _.debounce
.
You wrap your method with it and pass the milliseconds you want to wait.
As for the minimum length of the input, just invoke the new method only if the length is above 2.
Here is a small running example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: '',
inputValue: ''
};
this.updateMessage = _.debounce(this.updateMessage, 2000);
}
onChange = ({ target: { value } }) => {
this.setState({ inputValue: value });
if (value.length > 2) {
this.updateMessage(value);
}
}
updateMessage = message => this.setState({ message });
render() {
const { message, inputValue } = this.state;
return (
server call >> wait 2 seconds & min length of 2
{message}
);
}
}
ReactDOM.render( , document.getElementById('root'));