Day 27: Making A PokeDex: Day 2
Wrap up
Phew, that's day 2 done for PokeDex.
It's really starting to take shape now!
Tomorrow we'll finish it off.
At this point your code should look like this:
1const baseAPI = "https://pokeapi.co/api/v2/"; 2const flexContainer = document.getElementById("flex-container"); 3const placeholder = document.getElementById("placeholder"); 4const totalPokemon = document.getElementById("total-pokemon"); 5const modalBackdrop = document.getElementById("backdrop"); 6const modalTitle = document.getElementById("modal-title"); 7const modalImage = document.getElementById("modal-image"); 8 9let page = 0; 10let pokemonArray = []; 11 12const showModal = (pokemonId) => { 13 const foundPokemon = pokemonArray.find((p) => p.id === pokemonId); 14 15 modalTitle.innerText = foundPokemon.name; 16 modalImage.src = foundPokemon.sprites.front_default; 17 18 modalBackdrop.classList.remove("hidden"); 19}; 20 21const addCard = (pokemon) => { 22 const newCard = placeholder.cloneNode(true); 23 const loadingSpinner = newCard.querySelector(".lds-ring"); 24 25 loadingSpinner.remove(); 26 27 const title = newCard.querySelector(".title"); 28 title.innerText = pokemon.name; 29 30 const image = newCard.querySelector("img"); 31 image.src = pokemon.sprites.front_default; 32 33 const typesDiv = newCard.querySelector(".types"); 34 const types = pokemon.types.map((type) => type.type.name); 35 typesDiv.innerText = types.join(", "); 36 37 const weightDiv = newCard.querySelector(".weight"); 38 weightDiv.innerText = `${pokemon.weight} kg`; 39 40 newCard.id = pokemon.id; 41 42 newCard.onclick = () => showModal(pokemon.id); 43 44 flexContainer.appendChild(newCard); 45}; 46 47const getPokemonList = () => { 48 fetch(`${baseAPI}pokemon?limit=20&offset=${page * 20}`) 49 .then((res) => res.json()) 50 .then((data) => { 51 const fetchedPokemon = data.results; 52 53 const requests = fetchedPokemon.map((pokemon) => { 54 return fetch(pokemon.url) 55 .then((res) => res.json()) 56 .then((data) => { 57 pokemonArray.push(data); 58 console.log(pokemonArray); 59 addCard(data); 60 }); 61 }); 62 63 return Promise.all(requests); 64 }) 65 .finally(() => { 66 placeholder.classList.add("hidden"); 67 }); 68}; 69 70const showAndMovePlaceholder = () => { 71 placeholder.classList.remove("hidden"); 72 placeholder.remove(); 73 flexContainer.appendChild(placeholder); 74}; 75 76const nextPage = () => { 77 showAndMovePlaceholder(); 78 page++; 79 getPokemonList(); 80 totalPokemon.innerText = (page + 1) * 20; 81}; 82 83const dismissModal = (e) => { 84 console.log("here"); 85 if (e.currentTarget === e.target) { 86 modalBackdrop.classList.add("hidden"); 87 } 88}; 89 90modalBackdrop.onclick = dismissModal; 91 92getPokemonList();