React js Maximum update depth exceeded

Viewed 5074

i'm doing a condition for a update in my code. Basically, my code is working with this line

{this.state.index === 20 ? this.setState({index: 0,index2: 1}) : null }

(this line is in the render)

And now i want to do a comparaison with a variable. but when i'm doing

{this.state.index === this.state.list.length ? this.setState({index: 0,index2: 1}) : null }

i have the error

Error: 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.

I don’t understand the difference between the two lines, so I can’t understand why I have this mistake. Can someone explain to me why I have this? thx

UPDATE: my render :

 render() {
    return (
      <div>
          Search Film :
      <form onSubmit={this.mySubmitHandler}>
      <input
        type='text'
        onChange={this.myChangeHandler}
      />
      <input
        type='submit'
      />
      </form>
         {this.state.list.slice(this.state.index, this.state.index2).map(function(stock, id){
         return (<p key={id}> Title : {stock.title}  <br></br>release date : {stock.release_date}<br></br> popularité : {stock.popularity} <br></br> résumé : {stock.overview.substring(0,150)}...</p>)})}

         {this.state.index === this.state.list.length ? this.setState({index: 0,index2: 1}) : null }
     {this.state.index === -1 ? this.setState({index: 0,index2: 1}) : null }


        Top {this.state.list.length} Search : {this.state.index + 1}/ {this.state.list.length}
        <button onClick={() => {this.setState({index: this.state.index + 1,index2: this.state.index2 + 1})}}>Next Film</button>
    <button onClick={() => {this.setState({index: this.state.index - 1,index2: this.state.index2 - 1})}}>Previous Film</button>
    </div>

    );
  }
2 Answers

The problem was the setState in my rendering.

To fix the problem, i just changed the position of my condition.

Basically, in my rendering, i'm calling a function when i'm using the button

<button onClick={() => {this.checkclick()}}>Next Film</button>

and the function is just doing the same as before

checkclick() {
    this.setState({index: this.state.index + 1,index2: this.state.index2 + 1})
    if (this.state.index === this.state.list.length)
      this.setState({index: 0,index2: 1})
  }

When I do not set a path in the router, I face this problem. After that I used the path name in the PrivateRoute of the router and it worked.

Wrong:

without path name

Right:

with path name

Related