Build a Pokémon Search App Project - Build a Pokémon Search App RED error

Tell us what’s happening: One test is not passing. RED. Any hints/advice would be greatly appreciated.

Error message given:
“// running tests”"
"When the #search-input element contains the value Red and the #search-button element is clicked, an alert should appear with the text Pokémon not found.
“// tests completed”
“// console output”
“[Error: TypeError: alertMessage is undefined]”

Your code so far

const getPokemon = async () => {
  try {
    // Obtain the Pokémon name or ID from the search input field
    const pokemonNameOrId = searchInput.value.toLowerCase();

    // Fetch Pokémon data from the API based on the provided name or ID
    const response = await fetch(
      `https://pokeapi-proxy.freecodecamp.rocks/api/pokemon/${pokemonNameOrId}`
    );

    // Check if the response is ok
    if (!response.ok) {
      // If response is not ok, throw an error
      throw new Error('Pokémon not found');
    }

    const data = await response.json();

    // Set Pokémon information in the DOM
    pokemonName.textContent = `${data.name.toUpperCase()}`;
    pokemonID.textContent = `#${data.id}`;
    weight.textContent = `Weight: ${data.weight}`;
    height.textContent = `Height: ${data.height}`;
    spriteContainer.innerHTML = `
      <img id="sprite" src="${data.sprites.front_default}" alt="${data.name} front default sprite">
    `;

    // Set Pokémon stats in the DOM
    hp.textContent = data.stats[0].base_stat;
    attack.textContent = data.stats[1].base_stat;
    defense.textContent = data.stats[2].base_stat;
    specialAttack.textContent = data.stats[3].base_stat;
    specialDefense.textContent = data.stats[4].base_stat;
    speed.textContent = data.stats[5].base_stat;

    // Set Pokémon types in the DOM
    types.innerHTML = data.types
      .map(
        (obj) => `<span class="type ${obj.type.name}">${obj.type.name}</span>`
      )
      .join('');
  } catch (err) {
    // Reset display and notify user if Pokémon data is not found
    resetDisplay();
    alert('Pokémon not found');
    console.log(`Pokémon not found: ${err}`);
  }
};

screen image of error

WARNING

The challenge seed code and/or your solution exceeded the maximum length we can port over from the challenge.

You will need to take an additional step here so the code you wrote presents in an easy to read format.

Please copy/paste all the editor code showing in the challenge from where you just linked.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>PSA</title>
    <link rel="stylesheet" href="./styles.css" />
  </head>
  <body>
    <main>
      <h1>Pokémon Search App</h1>
      <div class="container">
        <form role="search" id="search-form">
          <label for="search-input">Search for Pokémon Name or ID:</label>
          <input type="text" name="pokemon" id="search-input" required />
          <button id="search-button">Search</button>
        </form>
        <div class="output">
          <div class="top-container">
            <div class="name-and-id">
              <span id="pokemon-name"></span>
              <span id="pokemon-id"></span>
            </div>
            <div class="size">
              <span id="weight"></span>
              <span id="height"></span>
            </div>
            <div id="sprite-container" class="sprite-container"></div>
            <div id="types"></div>
          </div>
          <div class="bottom-container">
            <table>
              <tr>
                <th>Base</th>
                <th>Stats</th>
              </tr>
              <tr>
                <td>HP:</td>
                <td id="hp"></td>
              </tr>
              <tr>
                <td>Attack:</td>
                <td id="attack"></td>
              </tr>
              <tr>
                <td>Defense:</td>
                <td id="defense"></td>
              </tr>
              <tr>
                <td>Sp. Attack:</td>
                <td id="special-attack"></td>
              </tr>
              <tr>
                <td>Sp. Defense:</td>
                <td id="special-defense"></td>
              </tr>
              <tr>
                <td>Speed:</td>
                <td id="speed" class="speed"></td>
              </tr>
            </table>
          </div>
        </div>
      </div>
      <script src="./script.js"></script>
    </main>
  </body>
</html>
// DOM element references for elements in the HTML document for displaying Pokemon characters
const pokemonID = document.getElementById('pokemon-id');
const pokemonName = document.getElementById('pokemon-name');
const spriteContainer = document.getElementById('sprite-container');
const types = document.getElementById('types');
const height = document.getElementById('height');
const weight = document.getElementById('weight');
const hp = document.getElementById('hp');
const attack = document.getElementById('attack');
const defense = document.getElementById('defense');
const specialAttack = document.getElementById('special-attack');
const specialDefense = document.getElementById('special-defense');
const speed = document.getElementById('speed');
const searchForm = document.getElementById('search-form');
const searchInput = document.getElementById('search-input');

/**
 * Asynchronous function to fetch and display Pokémon information based on user input.
 * - Uses the value from the search input field to query the Pokémon API.
 * - Updates the DOM with the retrieved Pokémon information, including name, ID, weight, height, stats, sprite, and types.
 * - Handles errors by resetting the display and providing a user alert if Pokémon data is not found.
 */
const getPokemon = async () => {
  try {
    // Obtain the Pokémon name or ID from the search input field
    const pokemonNameOrId = searchInput.value.toLowerCase();

    // Fetch Pokémon data from the API based on the provided name or ID
    const response = await fetch(
      `https://pokeapi-proxy.freecodecamp.rocks/api/pokemon/${pokemonNameOrId}`
    );

    // Check if the response is ok
    if (!response.ok) {
      // If response is not ok, throw an error
      throw new Error('Pokémon not found');
    }

    const data = await response.json();

    // Set Pokémon information in the DOM
    pokemonName.textContent = `${data.name.toUpperCase()}`;
    pokemonID.textContent = `#${data.id}`;
    weight.textContent = `Weight: ${data.weight}`;
    height.textContent = `Height: ${data.height}`;
    spriteContainer.innerHTML = `
      <img id="sprite" src="${data.sprites.front_default}" alt="${data.name} front default sprite">
    `;

    // Set Pokémon stats in the DOM
    hp.textContent = data.stats[0].base_stat;
    attack.textContent = data.stats[1].base_stat;
    defense.textContent = data.stats[2].base_stat;
    specialAttack.textContent = data.stats[3].base_stat;
    specialDefense.textContent = data.stats[4].base_stat;
    speed.textContent = data.stats[5].base_stat;

    // Set Pokémon types in the DOM
    types.innerHTML = data.types
      .map(
        (obj) => `<span class="type ${obj.type.name}">${obj.type.name}</span>`
      )
      .join('');
  } catch (err) {
    // Reset display and notify user if Pokémon data is not found
    resetDisplay();
    alert('Pokémon not found');
    console.log(`Pokémon not found: ${err}`);
  }
};

/**
 * Function to reset the display by clearing Pokémon information from the DOM elements.
 * - Removes the Pokémon sprite element if it exists.
 * - Clears text content from elements displaying Pokémon name, ID, types, height, weight, and stats.
 */
const resetDisplay = () => {
  const sprite = document.getElementById('sprite');
  if (sprite) sprite.remove();

  // reset stats
  pokemonName.textContent = '';
  pokemonID.textContent = '';
  types.innerHTML = '';
  height.textContent = '';
  weight.textContent = '';
  hp.textContent = '';
  attack.textContent = '';
  defense.textContent = '';
  specialAttack.textContent = '';
  specialDefense.textContent = '';
  speed.textContent = '';
};

/**
 * Event listener attached to the search form submission.
 * - Prevents the default form submission behavior.
 * - Calls the getPokemon function to fetch and display Pokémon information based on user input.
 */
searchForm.addEventListener('submit', (e) => {
  e.preventDefault();
  getPokemon();
});

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:123.0) Gecko/20100101 Firefox/123.0

Challenge Information:

Build a Pokémon Search App Project - Build a Pokémon Search App

Please share your complete HTML and JavaScript code. It’s necessary to reproduce the working state.

1 Like

I do not have enough information to help you right now. Please provide your HTML and the rest of your Javascript code so we can debug it.

1 Like

Thankyou Sanity, I have supplied the html & js code within the forum post.

Thankyou a2937, I have supplied the html & js code within the forum post.

Hmm, this is strange then, but for me all tests are passing with your code…

Could it be possible that you have some browser extension that’s impacting the test?

1 Like

I am using FireFox Browser v123.0

Which browser and version are you using to ‘run’ my code?

I have just installed the Chrome browser for linux
v122.0.6261.94(Official Build)(64-bit)
I signed into fCC with my credentials
I deleted the current code within the html, css, js sections.
Uploaded the code again
Ran the tests, and the same error! ‘Red’ failed I am confused :frowning:
here is a screen image

I’m not sure if it will work, but try removing the console.log

1 Like

Thanks,
I tried removing the “console.log(Pokemon not found: ${err});”
ran the code again; (within the chrome browser) and same error!
I don’t understand why the try...catch isn’t triggering when ‘Red’ is entered.

What does resetDisplay do? Perhaps put that line after the alert

hi ambradnum,
thanks for your advice.
function “const resetDisplay = () => {}” this will Reset display and notify user if Pokémon data is not found.
I moved the line so that it is executed after the alert() statement; re-ran the test…
…wahoo! it passed :slight_smile:

1 Like

Note - it’s best practice to post actual code instead of screenshots

Note to anyone reading this, I think the test might be bugged or something. I passed the challenge, then instead of submitting I went back and removed some of my comments, and then this test wouldn’t pass even though it worked exactly as it said. What worked for me was to make some inconsequential change in the editor to reset it, then search for 3 different pokemon, then press save, then run the tests again. Then it worked ¯_(ツ)_/¯

If you have a question about a specific challenge as it relates to your written code for that challenge and need some help, click the Ask for Help button located on the challenge (it looks like a question mark). This button only appears if you have tried to submit an answer at least three times.

The Ask for Help button will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.

Thank you.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.