0

How could we use a setState inside setTimeout. I declared a property inside constructor function. I used this.setState({ count: index }); inside setTimeout it throws an error like Uncaught TypeError: this.setState is not a function

constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
    this.onMouseDown = this.onMouseDown.bind(this);
  }
onMouseDown() {
    this.timer();
  }
timer() {
    for (var i = 1; i <= 90; i++) {
      (function(index) {
        setTimeout(function() {
          this.setState({ count: index });
        }, index * 10);
      })(i);
    }
  }

I tried a lot don't know how to fix this. And why it is wrong?.Please get me out of this problem..

htoniv
  • 1,658
  • 21
  • 40
  • 1
    Also relevant: https://stackoverflow.com/questions/42650102/react-this-setstate-is-not-a-function-inside-settimeout – ivarni Dec 10 '17 at 10:09

1 Answers1

0

this is not refering the compnent this.setState is defined on component this

 timer() {
    const objThis  = this; //store this.
        for (var i = 1; i <= 90; i++) {
          (function(index) {
            setTimeout(function() {
              objThis.setState({ count: index });
            }, index * 10);
          })(i);
        }
      }
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53