I have a main app render a GameCard component. I am storing an array of objects fetched in a useEffect to state with useState and setInterval to refetch every minute. I can log out the props passed in my GameCard component, but it will not render the mapped data. It will show the loading correctly and removes it once loaded, it will also show "Games" in a div. It shows what I have in state passed in props with React Devtools. I have no errors either. I feel like I almost have it or I've written this completely wrong.
I have check the docs but this might be a special case due to how I want to destructure the array in GameCard. I add the whole array of nested objects to state and destructure them in the return of GameCard.
Note: This api requires two separate fetches, one to get an array of links (not shown) and one to loop over each link to get each game's data.
App.js
import React, { useState, useEffect } from "react";
import "./App.css";
import getGameLinks from "./utils/getGameLinks";
import GameCard from "./GameCard";
function App() {
const [games, setGames] = useState([]);
const [link, setLink] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const getGameData = async () => {
setLoading(true);
if (link.length === 0) {
const links = await getGameLinks(); // gets list of game links, required to get each game's data
setLink(links);
} else {
const gameArray = [];
link.forEach((link) => {
fetch(link)
.then((res) => res.json())
.then((out) => gameArray.push(out));
});
const newGameArray = gameArray.sort((a, b) => a.gamePk > b.gamePk); // does not work
setGames(newGameArray);
setLoading(false);
}
const timer = setInterval(getGameData, 60000);
return () => {
clearInterval(timer);
};
};
getGameData();
}, [link]);
return (
<div className="App">
<h1>Gameday</h1>
<GameCard games={games} loading={loading} />
</div>
);
}
export default App;
GameCard.js
import React from "react";
const GameCard = ({ games, loading }) => {
if (loading) return <p>Loading...</p>;
if (!loading)
return (
<div>
<p>Games</p>
{games.map((games) => (
<p key={games.gamePk}>
{games.gameData.teams.home.name} vs {games.gameData.teams.away.name}
</p>
))}
</div>
);
};
export default GameCard;