I am trying to display data of basketball players through a API fetch request in React. The API has data I can access such as firstname, lastname, teamname, teamlogo, and so on… I have the fetch request set up in my main App.jsx page and i then feed a prop i also have on App.jsx from my useState const named ‘players’, to the rendered cards page where i have simple cards logic to render the information of different players on each card. The issue is that i either get no errors and no displayed data from the API, or an error as follows for the first data property.
MultiplePlayerCards.jsx:59 Uncaught TypeError: Cannot read properties of undefined (reading ‘firstname’)
for clarity this is my App.jsx:
import { useState, useEffect } from "react";
import MultiplePlayerCards from "./components/MultiplePlayerCards";
import PlayerCard from "./components/PlayerCard";
import "./App.css";
const App = () => {
const [players, setPlayers] = useState([]);
useEffect(() => {
const fetchMyEvents = async () => {
try {
const response = await fetch(
"https://api-nba-v1.p.rapidapi.com/players/statistics?game=8133",
{
method: "GET",
headers: {
"x-rapidapi-key": "123456789",
"x-rapidapi-host": "api-nba-v1.p.rapida pi.com",
},
},
);
if (response.ok) {
const data = await response.json();
setPlayers([data]);
} else {
throw new Error("Failed to fetch players");
}
} catch (error) {
console.error("Error fetching players:", error);
}
};
fetchMyEvents();
}, []);
return (
<>
<MultiplePlayerCards players={players} />
</>
);
};
export default App;
and the file where i have the mapping for each data property i want to display from the players, which is also fed into another card component, which i have for other purposes mainly animations.
import React from "react";
import { useState, useEffect } from "react";
import "./styles.css";
import PlayerCard from "./PlayerCard";
import { playerImages } from "../../player-images";
const MultiplePlayerCards = () => {
return (
<div className="app">
<h1>NBA Player Stats</h1>
<div className="car-container">
{players && players.length > 0 ? (
players.map((player, index) => (
<PlayerCard
key={index}
firstName={player.player.firstname}
lastName={player.player.lastName}
fullName={`${firstName} ${lastName}`}
teamName={player.player.teamName}
teamLogo={player.player.teamLogo}
points={player.player.points}
assists={player.player.assists}
rebounds={player.player.totReb}
minutes={player.player.min}
playerImage={playerImages[fullName]}
/>
))
) : (
<p>No players found</p>
)}
</div>
</div>
);
};
export default MultiplePlayerCards;
so far I have tried to access firstname
differently, with just player.firstname
instead of player.player.firstname
as this was the way i accessed it in a previous project where i just used vanilla JS, but still nothing worked.