First, render Pikachu data when the page loads. Here we use a helper function that can fetch and render any pokemon. The flexibility of this generic helper function will be useful for the search functionality.
const getPokemonData = (pokemonName) => {
const promise = fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`);
promise
.then((response) => response.json())
.then((data) => {
console.log(data);
// render the data
const img = document.querySelector("#pokemon-picture>img")
const p = document.querySelector("#pokemon-picture>p")
img.src = data.sprites.front_default;
p.textContent = data.name
})
.catch((error) => console.error(error.message));
}
const main = () => {
getPokemonData("pikachu");
}
main(); // running when the page loads
Next, we implement the form search such that it can also fetch pokemon data. Make sure to use the getPokemonData helper from the last step!
const searchForPokemon = (e) => {
// stop the reload/redirect
e.preventDefault();
const form = e.target;
const formData = new FormData(form);
const formObj = Object.fromEntries(formData);
console.log('here is your data:', formObj);
// use the helper function, passing in the form's pokemon data
getPokemonData(formObj.pokemon)
form.reset();
}
const main = () => {
getPokemonData("pikachu");
// add a submit event listener to the form
const form = document.querySelector("#pokemon-search-form")
form.addEventListener('submit', searchForPokemon)
}