Skip to content

Error: Too many re-renders. because i changed setState

error: Too many re-renders.
explaining code: (
iam maping array of object – in that mapping funtion i maked new array of objects( raiting = [..rating, {}] ) then set useState state to be that array of objects ( setRatingFinal([...rating]) ) and then final i display that – but iam getting error.
)
Can somebody write me answer for this, if its posible to write code in answer. Thanks.

var [ratingFinal, setRatingFinal] = useState([])
var rating = []

movies.map((movie, i) => {
  rating =  [...rating, {index: i, value: movie["IMDB Votes"] * movie["IMDB Rating"]}];
});

setRatingFinal([...rating])   **//because of this is error**


  return (
    <div>
      {ratingFinal.map((movie, i) => {
        <div key={i}>{movie.value}</div>
      })}
    </div>
  );
}

export default App;

the movies is array of 3021 objects – example of one object in that array –

{"IMDB Rating": 6.3, "IMDB Votes": 365}

i tryed without var rating just with ratingFinal, but and that dont work- like this:

 var [ratingFinal, setRatingFinal] = useState([])
    
    movies.map((movie, i) => {
      setRatingFinal([...ratingFinal, {index: i, value: movie["IMDB Votes"] * movie["IMDB Rating"]}]);
    });
    
      return (
        <div>
          {ratingFinal.map((movie, i) => {
            <div key={i}>{movie.value}</div>
          })}
        </div>
      );
    }
    
    export default App;

Answer

make timeout and move setRatingFinal([...rating]) in timeout minimum 100ms, and you must make one objec with value because in first render it will not show (it can’t read property of undefined)

 var [ratingFinal, setRatingFinal] = useState([{value: 'something'}])