How to change the state from two different function call?

Aditya Joshi Source

How can i modify state from two different function call? Following code gives me error'Maximum update depth exceeded.'

class App extends Component {
   // fires before component is mounted
   constructor(props) {

    // makes this refer to this component

    // set local state
    this.state = {
        date: new Date(),
        counter :0,
    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
    this.handleClick = this.begin.bind(this)

    handleClick() {
      if(this.state.activeQuestion <= myQuestion.length){
        this.setState(prevState => ({
          counter: this.state.counter + 1,

render() {
    return (
    <div className="App">
        <div id = "myQuiz">
          <div class ="intro {{  (activeQuestion > -1)? 'inactive':'active' }}">
            <p>Click begin to test your knowledge</p>
            <p class = "btn" onClick={this.begin('begin')}>Begin</p>
            <button onClick={this.handleClick}></button>

What will be the right way to change state from different function call?



answered 1 week ago Prakash Sharma #1

You are not passing function to cllick handler. Instead you are calling the function like


This line is causing an infinite loop because calling this function is updating the state, which in turn is calling the render function. Change this to


If you want to pass the parameter to handler then

onClick={() => this.begin('begin')}

answered 1 week ago trixn #2

You have multiple issues in your code.

  1. You override this.handleClick with the bound version of begin() in your constructor and this.begin will still not be bound to this.

  2. Where does myQuestion come from in the constructor? Is it a globally scoped variable?

  3. In your handleClick() you do not use the prevState to calculate the next state. Instead you use this.state which may lead to bad behavior if react batches multiple calls to setState().

  4. Why do you use an onClick handler on a paragraph? Shouldn't this be a button?

  5. You have to use className instead of class in jsx because class is a reserved keyword in javascript.

  6. Also the class you are trying to set will be literally the text intro {{ (activeQuestion > -1)? 'inactive':'active' }}. This is for sure not what you where trying to achieve.

comments powered by Disqus