3. Building a Fetching App
Video
Watch the full build tutorial here!
Setup
Create a new repository and clone it down. CD and then:
cd into app and npm i
Remove the starter code.
Plan
Before you build anything, draw a wireframe
Then plan out the logic:
When the page loads:
fetch pikachu (make sure to catch any errors)
render pikachu data to the screen
add an event listener for the form
When the form is submitted:
grab data from the form
use that data to fetch a new pokemon (make sure to catch any errors)
render that pokemon to the screen
HTML
First, we'll create the structure. We want:
An
h1heading with some titleA
formto search for a pokemon. It should have:An
h2heading with a form titleA
labelandinput:textcombo for the pokemon name.A
buttonto submit the form
A
sectionto display pokemon information. It will have two sections and we'll make itdisplay: flexto put them side by side:A
divto display the pokemon picture and nameA
divwith aulto display the pokemon stats
Here's the HTML we came up with, added to the div#app container:
JavaScript Separation of Concerns
Rather than writing all of your code in one place, separate your code into three files:
src/fetching-helpers.js- exports functions related to fetching data from specific Web APIssrc/dom-helpers.js- exports functions related to dom manipulationsrc/main.js- pulls together functions from helper files and invokes them. Defines event handlers if needed.
After creating these files, we can put the outline of some functions inside:
Start with fetching data from the API since that the data we get back will tell us what information we can render. We'll use pikachu as the test input for now.
Fetching
In fetching-helpers.js, we can create a fetchPokemon function that takes in a pokemonName and searches the PokeAPI for that pokemon:
This file only cares about fetching the pokemonData from the response body's ReadableStream. Once we get that data, this function has done its job. It will return pokemonData wrapped in a Promise.
Putting it Together
Remember how we set up showPokemon in dom-helpers.js?
Because of this forward thinking, in main.js, we can already link up fetchPokemon with showPokemon by invoking showPokemon when the promise returned by fetchPokemon resolves.
The pokemonData that the fetchPokemon promise resolves to will be passed to and printed out by showPokemon.
Rendering
In dom-helpers.js, the final step is rendering the pokemon! This requires us to look at the API more closely to see the structure of the data we're dealing with.
Printing out the pokemonData is a helpful way to see the data structure first. We can see that we care about the following data:
pokemonData.sprites— an object of pokemon imagespokemonData.name— the name of the pokemon
Adding Form Handling
Because of the beautiful separation of concerns, adding in form functionality is easy. We just grab the pokemonName data from the form, pass it to fetchPokemon, and showPokemon when the promise resolves!
Last updated