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

Time:12-03

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;

CodePudding user response:

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'}])

CodePudding user response:

You are using the .map() method incorrectly - if you'd like to keep the syntax use .forEach().

Map returns a new array so the usage is:

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

setRatingFinal(rating)
  • Related