Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React setTimeout hooks onclick

It is giving an error Cannot read property 'handleCheck' of undefined when I click on next button. Can anyone please help?Thanks in advance

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  state = { check: false };
  handleCheck = () => {
    console.log("hello");
    this.setState({ check: !this.state.check });
  };
  componentDidMount() {
    setTimeout(() => {
      this.handleCheck();
    }, 10000);
  }
  timer() {
    setTimeout(() => {
      this.handleCheck();
    }, 10000);
  }
  render() {
    return (
      <div>
        <p>hello</p>
        {this.state.check ? (
          <button onClick={this.timer}>Next</button>
        ) : (
          <div>button not showing </div>
        )}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("container"));
like image 676
mamadgi aishwarya Avatar asked Mar 17 '26 19:03

mamadgi aishwarya


1 Answers

make it an arrow function:

  timer = () => {
    setTimeout(() => {
      this.handleCheck();
    }, 1000);
  }

so it's bound to the parent scope

like image 173
Red Baron Avatar answered Mar 20 '26 08:03

Red Baron