rakibtg
rakibtg

Reputation: 5901

Implementing debounce in react es6

I am trying to implement debounce in a search form, frontend framework is react js, using es6.

Few method that are related to this debounce functionality are:

handleSearchForm( event ) {
  this.setState( {
    searchAble: event.target.value
  } )
}

search() {
  console.log( this.state.searchAble )
}

I am using lodash debounce in the input field onChange property, and setting the state in onKeyUp property, like this:

<input type="text" className="form-control input-sm" placeholder="Search item by SKU, Price, Title etc..."
  onKeyUp={ this.handleSearchForm.bind( this ) }
  onChange={
    _.debounce( () => {
      this.search( this )
    }, 2050 ).bind( this )
  }
/>

So the idea is on keyup it will set the value in state called 'searchAble' and onChange this will call the method search to perform the search. But its not working properly, it still calling the search method multiple time completing the typings.

What i am missing here?

Upvotes: 1

Views: 876

Answers (1)

rafat ahmed
rafat ahmed

Reputation: 132

https://github.com/nkbt/react-debounce-input

please go the repository and follow the instruction. I think it may help you and remember one thing

"Notification of current value will be sent immediately by hitting Enter key. Enabled by-default. Notification value follows the same rule as with debounced notification, so if Length is less, then minLength - empty value '' will be sent back."

example code

  <DebounceInput
  type="number"
  onChange={event => this.setState({value: event.target.value})}
  placeholder="Name"
  className="user-name" 
/>

Upvotes: 2

Related Questions