i have a problem on my fetching. i fetched API to my project, when i trying to use display on value, it doesn't work on the first click. at the second click the function will run good and everything works. when im trying to log in the fetching function everything works good, but, at the display function i get an error: also if i write a number of pokemon to search and click to search it doesnt work but, if i change it and click again, i will get the first pokemon value.
Uncaught TypeError: Cannot read properties of undefined (reading 'name')
im adding the function of the fetch and also the display function i can also send the git reposetory if anyone want to help. thenks
let fetetchPokemon = function (inputNum) {
fetch(`${pokemonApi}` `${inputNum}`)
.then((response) => response.json())
// .then((response) => console.log(response))
.then(
(response) =>
(pokemon = new Pokemon(
response.name,
response.sprites,
response.moves,
response.types,
response.abilities
))
)
// .then((pokemon) => console.log(pokemon.name));
// .then((pokemon) => console.log(pokemon.name))
.then(displayPokemon());
};
let displayPokemon = function () {
pokemonName.innerText = pokemon.name;
console.log(pokemon.name);
pokemonImg.src = pokemon.image.front_default;
displayMoves(pokemon.moves);
displayType(pokemon.types);
displayAbilities(pokemon.abilities);
};
there is also a bin to see the code: https://jsbin.com/puvotid/edit?html,css,js,output
CodePudding user response:
The display method must be placed same scope with variable assignment. So the method will look like
const fetetchPokemon = function (inputNum) {
fetch(`${pokemonApi}` `${inputNum}`)
.then((response) => response.json())
.then(
(response) => {
pokemon = new Pokemon(
response.name,
response.sprites,
response.moves,
response.types,
response.abilities
);
displayPokemon();
}
);
};
As answer below from @Mamoud, you should use async/await or callback invidually, not both
CodePudding user response:
use async
and await
to wait the results.
const fetchPokemon = async function(){
await fetch(...).then(...)
}