Currently, I am delving into the world of JavaScript and encountering an issue while attempting to fetch information from the Pokemon API. While I can successfully retrieve some data, I am facing a challenge when trying to access the second type of Pokemon. The fetching process seems to work fine for the first type, but not for the second.
I suspect that the issue lies in the fact that not all Pokemon have two types (apiTypes
). Unfortunately, I am unsure how to display or render the second type.
If you want to check out the JSON data, here is the link:
/ https://pokebuildapi.fr/api/v1/pokemon
[
{
"id": 1,
"pokedexId": 1,
"name": "Bulbizarre",
"image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png",
"sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png",
"slug": "Bulbizarre",
"stats": {
"HP": 45,
"attack": 49,
"defense": 49,
"special_attack": 65,
"special_defense": 65,
"speed": 45
},
"apiTypes": [
{
"name": "Poison",
"image": "https://static.wikia.nocookie.net/pokemongo/images/0/05/Poison.png"
},
{
"name": "Plante",
"image": "https://static.wikia.nocookie.net/pokemongo/images/c/c5/Grass.png"
}
],
Regarding my current code: If I use
<img src="${pokemon.apiTypes[0].image}" id="type">
, it successfully displays the image for the first type.
However, when I replace it with <img src="${pokemon.apiTypes[1].image}" id="type">
, it fails to render the image for the second type.
const pokemonContainer = document.querySelector('.pokemon-container')
let pokemonData = []
async function fetchPokemon(){
await fetch("https://pokebuildapi.fr/api/v1/pokemon")
.then((res) => res.json())
.then((data) => pokemonData = data);
console.log(pokemonData);
pokemonDisplay()
};
function pokemonDisplay(){
pokemonContainer.innerHTML = pokemonData
.map((pokemon) =>
`
<div class="card">
<h2>#${pokemon.id} ${pokemon.name}</h2>
<img src="${pokemon.image}" id="pic">
<img src="${pokemon.apiTypes[0].image}" id="type">
<ul>
<li>PV ${pokemon.stats.HP}</li>
<li>Att ${pokemon.stats.attack}</li>
<li>Def ${pokemon.stats.defense}</li>
</ul>
</div>
`
).join("")};
window.addEventListener('load', fetchPokemon);