Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(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?

like image 645
Ben Avatar asked May 01 '26 09:05

Ben


1 Answers

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' />
like image 76
Ben Avatar answered May 03 '26 22:05

Ben