Hello, I am trying to create a pokedex project and I have run into an issue where I cannot get my code to output multiple Types listed in the API.
for example if a pokemon has 2 types it will only render the last one to the HTML, I think its because I created a loop and it only lists the last item in the loop. I can’t figure out how to get it to loop through and list each one.
This is the code. any help would be awesome!
let searchInput = document.getElementById('search-input');
const submitBtn = document.getElementById('submit');
const viewContainer = document.getElementById('viewContainer');
//Axios reques tto API
const fetchData = async (searchTerm) => {
const response = await axios.get(
`https://pokeapi.co/api/v2/pokemon/${searchTerm}`
);
return response.data;
};
//Event listeners for buttons an selections.
submitBtn.addEventListener('click', async () => {
const reply = await fetchData(searchInput.value);
searchInput.value = '';
const type = reply.types;
const typesArr = [];
let listType;
console.log(reply.types);
for (let i = 0; i < type.length; i++) { // <----This is the loop I am having trouble with
typesArr[i] = type[i].type.name;
listType = `<li>${typesArr[i]}</li>`; }
console.log(typesArr);
viewContainer.innerHTML = `<h2>${
reply.name.charAt(0).toUpperCase() + reply.name.slice(1)
}</h2>
<img src="${reply.sprites.other['official-artwork'].front_default}">
<ul>
${listType}
</ul>`;
});