I'm learning about rest APIs and async/await, so I'm just doing a tiny project with pokeapi.
I got an event listener on "input" that calls the API and then fills in the html fields.
The problem is, when an id is inserted eg "123" this will make three requests, fetchPokemon("1"), fetchPokemon("12") and fetchPokemon("123"), for now that is not a problem. But what it sometimes does is that the second request "12" finishes after the third request "123" so the final filled in html field is with the data from "12" request.
Is there an easy way around this to make it fill in always the last made request?
const pokemonId = document.getElementById("pokemon-id");
const pokemonName = document.getElementById("pokemon-name");
const pokemonType = document.getElementById("pokemon-type");
const pokemonHeight = document.getElementById("height");
const pokemonWeight = document.getElementById("weight");
const pokemonSearch = document.getElementById("pokemon-search");
async function fetchPokemon(idOrName) {
const endpoint = "https://pokeapi.co/api/v2/pokemon/";
const response = await fetch(endpoint + idOrName);
if (!response.ok) return null;
return response.json();
}
function fillPokemonFields(pokemon) {
if(!pokemon) return;
pokemonId.textContent = pokemon.id;
pokemonName.textContent = pokemon.name;
pokemonType.textContent = pokemon.type;
pokemonHeight.textContent = pokemon.height;
pokemonWeight.textContent = pokemon.weight;
}
pokemonSearch.addEventListener("input", async function () {
let input = this.value;
let pokemon;
// TODO validation
pokemon = await fetchPokemon(input);
fillPokemonFields(pokemon);
});
html
<main>
<input type="text" id="pokemon-search">
<div id="pokemon-id"></div>
<div id="pokemon-name"></div>
<div id="pokemon-type"></div>
<div id="pokemon-height"></div>
<div id="pokemon-weight"></div>
</main>
.addEventListener
part. The input
event is almost identical to the change
event, which means everytime a user enters a key, it gets updated. This is why it makes 3 calls with 1, 12 and 123
Instead of input
use submit
on the form
yourFormElement.addEventListener("submit", function (e) {
// this is needed to avoid default functionality of the onsubmit method
e.preventDefault();
// do stuff here...
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.