I'm essentially brand new to React, so please bear with me if there are any strange or obvious mistakes that I am missing.
I am looking to create a small little project with the National Hockey League statistics API and unfortunately have run into an issue pretty early on.
Essentially, what this code is trying to do right now is to fetch all of the current team ID's through https://statsapi.web.nhl.com/api/v1/teams, and then loop through each team's response and use it's unique ID to store every player ID currently playing in the league https://statsapi.web.nhl.com/api/v1/teams/ID/roster.
The API requests seem to be working just fine, however I'm running into an issue where the check for loading seems to be functioning improperly. If I say, for example
{loading ? <p>Loading...</p> : <p>{playerList[0].jerseyNumber}</p>}
I am given a "Cannot read properties of undefined" error message.
Is the way I attempted to signify loading incorrect? Is there a better way to be certain that the API requests are 100% finished before accessing the data?
Here is my code:
function App() {
const [playerList, setPlayerList] = useState([]);
const [loading, setLoading] = useState(true);
useEffect (() => {
fetch("https://statsapi.web.nhl.com/api/v1/teams")
.then((teamsResponse) => teamsResponse.json())
.then((teamsData) => {
const teams = teamsData.teams;
teams.forEach((team) => {
fetch("https://statsapi.web.nhl.com/api/v1/teams/" + team.id + "/roster")
.then((teamResponse) => teamResponse.json())
.then((teamData) => {
const roster = teamData.roster
roster.forEach((player) => {
setPlayerList((oldList) => [...oldList, player]);
});
});
});
});
setLoading(false);
}, []);
return (
<div>
{loading ? <p>Loading...</p> : playerList && <p>{playerList[0].jerseyNumber}</p>}
</div>
);
}