I am facing an issue while trying to map the data from an API result in order to display it. When I run my code, the console displays TypeError: pokemons.map is not a function. Strangely enough, I have implemented a similar functionality in another script and it works perfectly fine there. I'm puzzled as to why .map function is not working this time.
const result = document.getElementById('result');
const form = document.querySelector('form');
let pokemons = [];
async function fetchPokemon() {
fetch(`https://pokeapi.co/api/v2/pokemon/ditto`)
.then((res) => res.json())
.then((data) => (pokemons = data));
console.log(pokemons)
};
fetchPokemon();
function pokemonDisplay() {
result.innerHTML = pokemons.map(
(pokemon) =>
`
<h2>${pokemon.forms[0].name}</h2>
`
)
}
form.addEventListener('submit', (e) => {
e.preventDefault();
fetchPokemon().then(() => pokemonDisplay());
})
console.log(result);
<div class="app">
<form action="">
<label for="search">Enter the name of a Pokemon (in English)</label>
<input type="text" id="search" placeholder="e.g. ditto">
</form>
<ul id="result"></ul>
</div>