Using a debouncer with a React event

I have an onchange event for the field that needs to be canceled, I use underscore for this, however, when I use the debouncer, the event passed to the React handler looks deprecated.

<div className='input-field'>
  <input onChange={_.debounce(this.uriChangeHandler.bind(this), 500)} id='source_uri' type='text' name='source_uri' autofocus required />
  <label htmlFor='source_uri'>Website Link</label>
</div>

uriChangeHandler(event) {
    event.preventDefault();
    let uriField = $(event.target);
    let uri = uriField.val();
    this.setState({
        itemCreateError: null,
        loading: true
    });
    this.loadUriMetaData(uri, uriField);
}

I get this error: Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're calling preventDefault on a released/nullified synthetic event. This is a no-op. See https://fb.me/react-event-pooling for more information.

Using onchange without a debutator works great.

+4
source share
4 answers

in your case it may help

class HelloWorldComponent extends React.Component {
  uriChangeHandler(target) {
    console.log(target)
  }

  render() {
    var myHandler = _.compose(
      _.debounce(this.uriChangeHandler.bind(this), 5e2),
      _.property('target')
    );
    return (      
      <input onChange={myHandler}  />
    );
  }
}

React.render(
  <HelloWorldComponent/>,
  document.getElementById('react_example')
);

Jsbin

You can also use _.cloneinstead _.property('target')if you want to get the full event object.

EDITED

React , event.persist(), React doc:

, event.persist() , , .

e => e.persist() || e _.clone JSBin

+2

, github, . debounce debounceEventHandler, debounced.

function debounceEventHandler(...args) {
  const debounced = _.debounce(...args)
  return function(e) {
    e.persist()
    return debounced(e)
  }
}

<Input onChange={debounceEventHandler(this.handleInputChange, 150)}/>

+7
class HelloWorldComponent extends Component {
    _handleInputSearchChange = (event) => {
        event.persist();
        _.debounce((event) => {
            console.log(event.target.value);
        }, 1000)(event);
    };

    render() {
        return (
            <input onChange={this._handleInputSearchChange}  />
        );
    }
}
+1

, , . _.debounce ( , debouncing), , 500 . , - :

  • _.debounce() - 500
  • React event
  • event.stopPropagation() .

, : call event.stopPropagation() , ( ) .

Side note: this will still be a problem even with your own events. By the time your handler is actually called, the event would have already propagated. React just does a better job, warning you that you did something strange.

0
source

Source: https://habr.com/ru/post/1628996/


All Articles