0

This works:

    // Toggle the state every second
    setInterval(
      () => {
      this.setState(previousState => {
        return { isShowingText: !previousState.isShowingText };
      });
    }, 1000);
  }

This does not work:

    // Toggle the state every second
    setInterval(
      function() {
      this.setState(previousState => {
        return { isShowingText: !previousState.isShowingText };
      });
    }, 1000);
  }

I am expecting that if i replace () => {...} with function() {...} the above code should still work, but instead, I am getting the error that "undefined is not a function". Isn't the arrow syntax just shorthand for writing the function keyword?

Staxks
  • 143
  • 6
  • 3
    An arrow function inherits the `this` context from wherever it is defined. But a function declared using `function` will have its own `this`. So the problem is that `this.setState` is undefined, which means you can't call it. See [this question](https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – CRice Apr 11 '18 at 22:14
  • A specific workaround for your problem would be to capture `this` in an explicitly named variable outside the inner function (e.g. `const cmp = this;`), then refer to that inside the inner function where `this` is shadowed. – Asad Saeeduddin Apr 11 '18 at 22:16

0 Answers0