0

I am trying to setup a debounce function which will handle an HTTP request function. The code is very similar to the following one, basically, I only changed the functions naming.

Firstly, I am using this debounce function.

function debounced(fn, delay) {
let timerId;
return function (...args) {
    if (timerId) {
        clearTimeout(timerId);
    }
    timerId = setTimeout(() => {
        fn(...args);
        timerId = null;
    }, delay);
}}

And there is the example code which is a basic React'js class.

var Example = React.createClass({
getInitialState: function () {
    return ({
        counter: 0
    });
},
clickEvt: function () {
    console.log("hey!!");
    this.setState({counter: this.state.counter + 1});
    return debounced(request(this.props.counter), 3000);
},

render: function () {
    return (
        <button onClick={this.clickEvt}>hit me</button>;
    );
}});

The problem is, the debounced function runs the request in every click that I make in that button. What's the problem?

urb
  • 924
  • 1
  • 13
  • 28

1 Answers1

0

You're recreating a debounced function every time you click so this won't work. You need to create it once and use it.

Your also directly invoking your function. This should work:

var Example = React.createClass({
getInitialState: function () {
    return ({
        counter: 0
    });
},
debouncedRequest: debounce(function() {
   request(this.props.counter);
}, 3000),
clickEvt: function () {
    console.log("hey!!");
    this.setState({counter: this.state.counter + 1});
    return this.debouncedRequest();
},

render: function () {
    return (
        <button onClick={this.clickEvt}>hit me</button>;
    );
}});
Axnyff
  • 9,213
  • 4
  • 33
  • 37
  • The function is called only after the 3000ms, therefore we can say that it's having the normal behaviour, although I am getting errors of scope as I can't access the value of this.props or even this.state inside of the debounceRequest. Do you know how to fix it? – urb Mar 10 '18 at 20:39
  • When you're calling your function, your losing the this. You need to find a way to bind this to your debounced function. I don't know what would be the proper way with createClass. As you are using ES6, why do you need use react the modern way with classes? – Axnyff Mar 11 '18 at 12:44
  • Actually, it works thanks. The main problem was the function that I was using was not implemented properly. – urb Mar 15 '18 at 10:04