Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my component throwing a "too many re-renders" error?

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

I couldn’t find where the loop is, I managed to check if the states are different from "null" I could only render the graph and avoid the error, but it persists, could someone help me?..

import React from "react";
import { useState } from "react";
import { Chart } from "react-google-charts";

export const StatusChart = (pokemon) => {
  const [hp, setHp] = useState(null);
  const [attack, setAttack] = useState(null);
  const [defense, setDefense] = useState(null);
  const [specialAtack, setSpecialAtack] = useState(null);
  const [specialDefese, setSpecialDefese] = useState(null);
  const [speed, setSpeed] = useState(null);

  console.log(
    pokemon.pokemon.map((e) => {
      console.log(e.base_stat);
      switch (e.stat.name) {
        case "hp":
          setHp(e.base_stat);
          break;
        case "attack":
          setAttack(e.base_stat);
          break;
        case "defense":
          setDefense(e.base_stat);
          break;
        case "special-attack":
          setSpecialAtack(e.base_stat);
          break;
        case "special-defense":
          setSpecialDefese(e.base_stat);
          break;
        case "speed":
          setSpeed(e.base_stat);
          break;
      }
    })
  );

  const data = [
    ["Status", "Value", { role: "style" }],
    ["HP", hp, "red"],
    ["Atack", attack, "orange"],
    ["Defese", defense, "green"],
    ["Special Atack", specialAtack, "gold"],
    ["Special Defense", specialDefese, "purple"],
    ["Speed", speed, "blue"],
  ];

  return (
    <>
      {hp ||
      attack ||
      defense ||
      specialAtack ||
      specialDefese ||
      speed === null ? null : (
        <Chart
          chartType="ColumnChart"
          width="100%"
          height="300px"
          data={data}
        />
      )}
    </>
  );
};

Github link:
https://github.com/yjdutra/pokedex-pokeapi

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This console.log with a map inside is doing many setStates at the same time, causing the UI to re-render at each "pokemon" entity that you have. This is causing the error.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading