Aditya Joshi
Aditya Joshi

Reputation: 245

How to change the state from two different function call?

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
    super(props);

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

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


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

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

Upvotes: 0

Views: 30

Answers (2)

Prakash Sharma
Prakash Sharma

Reputation: 16472

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

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

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

onClick={this.begin}

If you want to pass the parameter to handler then

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

Upvotes: 2

trixn
trixn

Reputation: 16309

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.

Upvotes: 0

Related Questions