Home > Net >  .map is not a function (api result)
.map is not a function (api result)

Time:10-27

I'm trying to map an api result to display the data but when I launch my code the console shows TypeError: pokemons.map is not a function but I do the same in another script and it's working there. I don't understand why this time .map doesn't work.

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">Entrez le nom d'un pokemon (en anglais)</label>
    <input type="text" id="search" placeholder="ex : ditto">
  </form>

  <ul id="result"></ul>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

https://pokeapi.co/api/v2/pokemon/ditto return object not array (Ditto pokemon). map is the function of Array, that is why you catch this error.

  • Related