I'm trying to make a React app to fetch data from the pokemon api (https://pokeapi.co/docs/v2#pokemon) and display it in a grid.
My component tree:
App -> Pokedex -> n(PokeCard -> PokeAvatar)
In the App component, I fetch the pokemon data, I get the 20 first results and map the resulting array to one where the URL of each Pokemon is also fetched (each Object inside of the Array has a 'name', 'url', and 'info' property). The info property holds all the data from each individual fetch.
After rendering the Pokedex with this array as props, in the Pokedex component I map the array to an array of elements containing only the data I want to display (name, and a few properties from the 'info' property).
Here's the code that raises the error:
export class Pokedex extends React.Component {
render() {
console.log("this.props.pokeArray:", this.props.pokeArray); // shows pokemons with the 3 properties
const elements = this.props.pokeArray.map((pokemon, i) => {
console.log(pokemon); // logs the pokemon without the info property
return (
<PokeCard
key={`poke${i}`}
id={pokemon.info.id} //error raised here: Cannot read property 'id' of undefined
name={pokemon.name}
types={pokemon.info.types}
sprite={pokemon.info.sprites["front_default"]}
/>
);
});
return (
<div className="pkdx-pokedex-container">
<h1>Pokedex</h1>
{elements}
</div>
);
}
}
Here's also the code from its parent element, App:
import "./App.css";
import { Pokedex } from "./components/Pokedex/Pokedex";
import { useQuery } from "react-query";
import { ReactQueryDevtools } from "react-query-devtools";
// *** Base API url
const url = "https://pokeapi.co/api/v2/pokemon";
// *** Async, because we need to have the data before second fetch
async function fetchPokemon() {
const response = await fetch(url);
const data = (await response.json()).results;
// *** Keep url of fetch and add new info property to each pokemon
data.forEach(async (poke) => {
const res = await fetch(poke.url);
poke.info = await res.json();
});
return data;
}
function App() {
const info = useQuery("fetchPokemon", fetchPokemon);
if (info.status === "success") {
console.log("pokeArray:", info.data); // each Pokemon has the three properties
return (
<div>
<Pokedex pokeArray={info.data} />;
<ReactQueryDevtools />
</div>
);
} else return null;
}
export default App;
I don't know if I'm missing something, but I don't understand why it doesn't show the 'info' property.