Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Maximum update depth exceeded

I am getting this error when I run my code.

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

And here's the code . it's referencing.

  69 | }
  70 | 
  71 | addQuestion = () => {
> 72 |   this.setState({numQuestions: this.state.numQuestions + 1});
  73 |  }
  74 | 
  75 | render() {

  131 | <div className="field">
  132 |     <div className="endButtons">
  133 |       <button id="addQuestionButton"
> 134 |         onClick={this.addQuestion()}>Add Question</button>
  135 |       <input
  136 |         type="submit"
  137 |         value="Submit"

   5 | import App from './App';
   6 | import registerServiceWorker from './registerServiceWorker';
   7 | 
>  8 | ReactDOM.render(<App />, document.getElementById('root'));
   9 | registerServiceWorker();
  10 | 
  11 | 

I set my stuff up the way the articles on the actual React site said to and it "came" with this neat console type thing, that's where I came up with the above code. I'm very new to React, JSX, and Javascript (and just programing in general) and I don't really understand what this means so if you could also explain a little that would be awesome.

Thanks!

like image 351
dorkycam Avatar asked Jul 05 '18 16:07

dorkycam


2 Answers

You are calling this.addQuestion in your render method, which in turn calls setState which will result in a new render, and the indefinite loop continues.

You want to give onClick a function reference, not call it directly.

<button id="addQuestionButton" onClick={this.addQuestion}>Add Question</button>
like image 71
Tholle Avatar answered Sep 20 '22 07:09

Tholle


this.addQuestion() invoked every time the component re-renders, thus causing a loop.

Change the method this.addQuestion() to () => this.addQuestion()

<button id="addQuestionButton" onClick={() => this.addQuestion()}>Add Question</button>
like image 23
Romeo Avatar answered Sep 21 '22 07:09

Romeo