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

前端 未结 1 495
梦毁少年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 (
          <div>
            <input placeholder="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'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.compat.js"></script>
    <div id="root"></div>

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