Using Lodash Debounce In React To Prevent Requesting Data As Long As The User Is Typing
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 input va
Solution 1:
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:
classAppextendsReact.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 (
<div><inputplaceholder="type something..."value={inputValue}onChange={this.onChange} /><hr/><div>server call >> wait 2 seconds & min length of 2</div><p>{message}</p></div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><scriptsrc="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.compat.js"></script><divid="root"></div>
Post a Comment for "Using Lodash Debounce In React To Prevent Requesting Data As Long As The User Is Typing"