Using Lodash debounce in React to prevent requesting data as long as the user is typing

前端 未结 1 497
梦毁少年i
梦毁少年i 2021-02-14 12:31

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

1条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-14 12:54

    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'));
    
    
    
    

    0 讨论(0)
提交回复
热议问题