Ivan Telles
Ivan Telles

Reputation: 1

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

How would I avoid the infinite loop issue?

I'm getting an error while rendering the following component:

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

TeamContent.js re-renders multiple times, how can I set an initial render on load?

Error given

TeamContent.js

import { useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  fetchTeamPlayers,
  fetchUpcomingGames,
  fetchPreviousGames,
  fetchLiveGames,
} from "../../../data/UserInfo/infoActions";
import TeamPlayers from "./TeamPlayers";
import TeamNext from "./TeamNext";
import TeamPrevious from "./TeamPrevious";
import LiveEvent from "./Live.js/LiveEvent";

function TeamContent(props) {
  console.log("test");
  let containsLiveGame = false;
  const dispatch = useDispatch();
  const liveGames = useSelector((store) => store.userInfo.live.games.all);
  const status = useSelector((store) => store.userInfo.playersLoadStatus);
  const UpcomingGamesstatus = useSelector(
    (store) => store.userInfo.upcomingGamesStatus
  );
  const previousGamesStatus = useSelector(
    (store) => store.userInfo.previousGamesStatus
  );
  const liveStatus = useSelector((store) => store.userInfo.live.games.status);

  liveGames.map((game) => {
    const verifyHomeTeam = +game.idHomeTeam === +props.teamID;
    const verifyAwayTeam = +game.idAwayTeam === +props.teamID;

    if (verifyAwayTeam || verifyHomeTeam) {
      containsLiveGame = true;
    }
  });

  // -----> request team data
  useEffect(() => {
    dispatch(fetchTeamPlayers(props.teamID));
    dispatch(fetchUpcomingGames(props.teamID));
    dispatch(fetchPreviousGames(props.teamID));
    dispatch(fetchLiveGames());
  }, [dispatch, props.teamID]);

  useEffect(() => {
    dispatch(fetchLiveGames());

    const interval = setInterval(() => {
      dispatch(fetchLiveGames());
    }, 30000);

    return () => clearInterval(interval);
  }, [dispatch]);

  return (
    <div className="teamDash">
      <div className="dashLeft">
        <div
          className="dashLeftHead"
          style={{
            backgroundImage: `url(${props.stadiumImg})`,
          }}
        >
          <div className="dashLeftHeadAbs"></div>
          <div className="dashLeftHeadIntro">
            <span>{props.stadiumName}</span>
            <h3>{props.teamName}</h3>
          </div>
        </div>
        {liveStatus !== "error" && containsLiveGame && <LiveEvent />}

        {status !== "error" && (
          <div className="dashLeftPlayers">
            <TeamPlayers />
          </div>
        )}

        <div className="dashLeftDesc">
          <p>{props.teamDesc}</p>
        </div>
      </div>
      <div className="dashRight">
        {UpcomingGamesstatus === "error" ? (
          console.log("unable to load upcoming games")
        ) : (
          <div className="upcomingGames">
            <TeamNext id={props.teamID} />
          </div>
        )}
        {previousGamesStatus === "error" ? (
          console.log("unable to load previous games")
        ) : (
          <div className="previousGames">
            <TeamPrevious />
          </div>
        )}
      </div>
    </div>
  );
}

export default TeamContent;

infoActions.js

import { API_URL } from "../Api";
import { infoActions } from "./infoSlice";

export function fetchTeams() {
  return (dispatch) => {
    dispatch(infoActions.loadStatusHandler({ status: "loading" }));
    async function getTeams() {
      try {
        const rq = await fetch(`${API_URL}Lookup_all_teams.php?id=4387`);
        const res = await rq.json();
        const data = res.teams;
        dispatch(infoActions.loadTeamsHandler({ teams: data }));
        dispatch(infoActions.loadStatusHandler({ status: "done" }));
      } catch (error) {
        dispatch(infoActions.loadStatusHandler({ status: "error" }));
      }
    }
    getTeams();
  };
}

export function fetchTeamPlayers(id) {
  return (dispatch) => {
    async function getPlayers() {
      dispatch(infoActions.statusPlayersHandler({ status: "loading" }));
      try {
        const rq = await fetch(`${API_URL}lookup_all_players.php?id=${id}`);
        const res = await rq.json();
        const data = res.player;
        dispatch(infoActions.loadPlayersHandler({ players: data }));
        dispatch(infoActions.statusPlayersHandler({ status: "done" }));
      } catch (error) {
        dispatch(infoActions.statusPlayersHandler({ status: "error" }));
      }
    }
    getPlayers();
  };
}

export function fetchUpcomingGames(id) {
  return (dispatch) => {
    dispatch(infoActions.statusUGHandler({ status: "loading" }));
    async function getGames() {
      try {
        const rq = await fetch(`${API_URL}eventsnext.php?id=${id}`);
        const res = await rq.json();
        const data = res.events;
        dispatch(infoActions.upcomingGamesHandler({ games: data }));
        dispatch(infoActions.statusUGHandler({ status: "done" }));
      } catch (error) {
        dispatch(infoActions.statusUGHandler({ status: "error" }));
      }
    }
    getGames();
  };
}

export function fetchPreviousGames(id) {
  return (dispatch) => {
    dispatch(infoActions.statusPGHandler({ status: "loading" }));
    async function getGames() {
      try {
        const rq = await fetch(`${API_URL}eventslast.php?id=${id}`);
        const res = await rq.json();
        const data = res.results;
        dispatch(infoActions.previousGamesHandler({ games: data }));
        dispatch(infoActions.statusPGHandler({ status: "done" }));
      } catch (error) {
        dispatch(infoActions.statusPGHandler({ status: "error" }));
      }
    }
    getGames();
  };
}

export function fetchLiveGames() {
  return (dispatch) => {
    dispatch(infoActions.statusLiveGames({ status: "loading" }));
    async function getGames() {
      try {
        const rq = await fetch(
          `https://www.thesportsdb.com/api/v2/json/40130162/livescore.php?l=4387`
        );
        const res = await rq.json();
        const data = res.events;
        dispatch(infoActions.statusLiveGames({ status: "done" }));
        dispatch(infoActions.loadLiveGames({ liveGames: data }));
      } catch (error) {
        dispatch(infoActions.statusLiveGames({ status: "error" }));
      }
    }
    getGames();
  };
}

Upvotes: 0

Views: 6099

Answers (1)

Andy
Andy

Reputation: 5414

Try remove dispatch from the array you passed to

useEffect(() => {
...
}, [dispatch, props.teamID])

and

useEffect(() => {
...
}, [dispatch])

dispatch is a function, and if you include it into the useEffect listener, the useEffect will trigger on every render

Upvotes: 2

Related Questions