Ben
Ben

Reputation: 5361

(react) debounce with arguments

I'm trying to debounce a function (using underscore's debounce) passed as a prop to a component. I've been able to do this in the past with the following:

  componentWillMount() {
    this.handleInputTextChangeDebounced = debounce(() => {
      console.log('I debounce!');
    }, 250);
  },

That works fine and dandy, but now I need to access the event argument (so I can get the value from the input) from the onChange which triggeres the handleInputTextChangeDebounced

e.g.:

  <input onChange={this.handleInputTextChangeDebounced} data-option='buildNumber' />

I can't simply use a ref because I have many form input options that I want to use with thise debounced function.

I tried to return the debounce as a function within the handleInputTextChangeDebounced which would receive the event, but that appears to stop the debouncing from working.

Suggestions?

Upvotes: 3

Views: 4248

Answers (1)

Ben
Ben

Reputation: 5361

Figured out a solution using two steps. I called a normal class function (handleInputTextChange) where I extracted the value from the input field, then I called the debounced function (handleInputTextChangeDebounced) separately.

handleInputTextChange(e) {
  this.handleInputTextChangeDebounced(e.target.value);
},

handleInputTextChangeDebounced: debounce((value) => {
  // do debounced stuff with value here...
}, 700),


<input onChange={this.handleInputTextChange} type='text' data-option='buildNumber' />

Upvotes: 1

Related Questions