30 Days Of JavaScript

Day 26: Making a PokeDex

Lesson 3: PokeDex 3

There are two ways of accomplishing this task, the first is to fire off the request to the Pokemon URL to get the Pokemon data and create it's card, and then do the same of the next until we get to the end of the list. The second is to create all the fetch() requests upfront, fire them all off together, collect the data back and then create the cards.

Let's do the first one and then look at the problem this causes.

Replace the // more code comment wit this:

1for (let pokemon of fetchedPokemon) {
2  fetch(pokemon.url)
3    .then((res) => res.json())
4    .then((data) => {
5      console.log(data);
6      // even more code to come
7    });
8}

This loops through our array of Pokemon, fires off a fetch() request for each one and prints the result.

Before we look at what's wrong here let's get some UI up and running, add this function to your code.

1const addCard = (pokemon) => {
2  const newCard = placeholder.cloneNode(true);
3  const loadingSpinner = newCard.querySelector(".lds-ring");
4
5  loadingSpinner.remove();
6
7  const title = newCard.querySelector(".title");
8  title.innerText = pokemon.name;
9
10  const image = newCard.querySelector("img");
11  image.src = pokemon.sprites.front_default;
12
13  newCard.id = pokemon.id;
14
15  flexContainer.appendChild(newCard);
16};

And then replace // even more code to come with:

1addCard(data);

Your full code should look like this now:

1const baseAPI = "https://pokeapi.co/api/v2/";
2const flexContainer = document.getElementById("flex-container");
3const placeholder = document.getElementById("placeholder");
4
5const addCard = (pokemon) => {
6  const newCard = placeholder.cloneNode(true);
7  const loadingSpinner = newCard.querySelector(".lds-ring");
8
9  loadingSpinner.remove();
10
11  const title = newCard.querySelector(".title");
12  title.innerText = pokemon.name;
13
14  const image = newCard.querySelector("img");
15  image.src = pokemon.sprites.front_default;
16
17  newCard.id = pokemon.id;
18
19  flexContainer.appendChild(newCard);
20};
21
22const getPokemonList = () => {
23  fetch(`${baseAPI}pokemon?limit=20&offset=0`)
24    .then((res) => res.json())
25    .then((data) => {
26      const fetchedPokemon = data.results;
27
28      for (let pokemon of fetchedPokemon) {
29        fetch(pokemon.url)
30          .then((res) => res.json())
31          .then((data) => {
32            console.log(data);
33            addCard(data);
34          });
35      }
36    });
37};
38
39getPokemonList();

Looking pretty good right?!

Well, let's look at the problem we have.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co