Think about states before the request
PokéAtlas requests data that is not included in the HTML. Between clicking a button and receiving a response, there may be a wait, a connection error or a missing resource.
An interface needs to distinguish initial, loading, result and error states. Loading feedback explains the wait; error feedback should help people understand and try again.
Check the response
async function getPokemon(name) {
const identifier = encodeURIComponent(name.trim().toLowerCase());
const response = await fetch(
'https://pokeapi.co/api/v2/pokemon/' + identifier
);
if (!response.ok) {
throw new Error('HTTP ' + response.status);
}
return response.json();
}
fetch does not automatically reject the promise for
an HTTP 404. That's why I check response.ok before
parsing the JSON.
Update a simple interface
<p id="status" role="status"></p>
<p id="result"></p>
const status = document.querySelector('#status');
const result = document.querySelector('#result');
async function showPokemon(name) {
status.textContent = 'Loading...';
result.textContent = '';
try {
const pokemon = await getPokemon(name);
result.textContent = pokemon.name;
status.textContent = 'Result available.';
} catch (error) {
status.textContent = 'Unable to load. Please try again.';
}
}
showPokemon('pikachu');
What a fuller interface still needs
If people can run several searches in succession, manage
outdated responses; you can cancel a previous request with
AbortController. Also validate the field,
distinguish errors and handle missing images.
I use textContent to display the name as text. This
example does not cover every production case. The Pikachu
endpoint was checked when preparing this article.