0

I'm trying to call setState inside a function inside a function. Here is my function.

//iohook Idle Functions.
    setIdleTimeout = (millis) => {
        var timeout = 0;
        //Adding iohook Event Listners.
        ioHook.start();
        ioHook.on('mouseclick', onActivity);
        ioHook.on('keypress', onActivity);
        ioHook.on('mousewheel', onActivity);
        ioHook.on('mousemove', onActivity);
        startTimer();

        function startTimer() {
            timeout = setTimeout(onExpires, millis);
        }

        function onExpires() {
            timeout = 0;
            alert("User Idle. Click 'OK' to dismiss this window and restart task timer.");
            this.setState({ isTimerRunning: false }); // <--- Here
        }

        function onActivity(event) {
            if (timeout) clearTimeout(timeout);
            else {
                console.log('Welcome Back.');
            }
            startTimer();
        }
    };

And I'm calling setIdleTimeout(5000) function outside this function.

But I'm getting this error.

Uncaught TypeError: this.setState is not a function at onExpires

I tried to change every function to arrow functions with no help. Can you guys help me sort this out ? Thanks,

  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Herohtar May 05 '19 at 05:28
  • Do `const self = this; function onExpires() { /*... */ self.setState(/*... */)}`. – connexo May 05 '19 at 05:33
  • turning the functions into variable-declared arrow functions should fix it for you – Derek May 05 '19 at 07:35

0 Answers0