Issue accessing an item in an array using the JavaScript API

Currently, I am delving into the world of JavaScript and encountering an issue while attempting to fetch information from the Pokemon API. While I can successfully retrieve some data, I am facing a challenge when trying to access the second type of Pokemon. The fetching process seems to work fine for the first type, but not for the second.

I suspect that the issue lies in the fact that not all Pokemon have two types (apiTypes). Unfortunately, I am unsure how to display or render the second type.

If you want to check out the JSON data, here is the link:

/ https://pokebuildapi.fr/api/v1/pokemon

[
  {
    "id": 1,
    "pokedexId": 1,
    "name": "Bulbizarre",
    "image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png",
    "sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png",
    "slug": "Bulbizarre",
    "stats": {
      "HP": 45,
      "attack": 49,
      "defense": 49,
      "special_attack": 65,
      "special_defense": 65,
      "speed": 45
    },
    "apiTypes": [
      {
        "name": "Poison",
        "image": "https://static.wikia.nocookie.net/pokemongo/images/0/05/Poison.png"
      },
      {
        "name": "Plante",
        "image": "https://static.wikia.nocookie.net/pokemongo/images/c/c5/Grass.png"
      }
    ],

Regarding my current code: If I use

<img src="${pokemon.apiTypes[0].image}" id="type">
, it successfully displays the image for the first type. However, when I replace it with
<img src="${pokemon.apiTypes[1].image}" id="type">
, it fails to render the image for the second type.

const pokemonContainer = document.querySelector('.pokemon-container')
let pokemonData = []

async function fetchPokemon(){
await fetch("https://pokebuildapi.fr/api/v1/pokemon")
.then((res) => res.json())
.then((data) => pokemonData = data);

console.log(pokemonData);

pokemonDisplay()
};

function pokemonDisplay(){
    pokemonContainer.innerHTML = pokemonData
    .map((pokemon) => 
    
    `
    <div class="card">
    <h2>#${pokemon.id}  ${pokemon.name}</h2>
    <img src="${pokemon.image}" id="pic">
    <img src="${pokemon.apiTypes[0].image}" id="type">
    <ul>
    <li>PV  ${pokemon.stats.HP}</li>
    <li>Att  ${pokemon.stats.attack}</li>
    <li>Def  ${pokemon.stats.defense}</li>
    </ul>
    </div>
    `
    
    ).join("")};

window.addEventListener('load', fetchPokemon);

Answer №1

To ensure the existence of pokemon.apiTypes[1].image, a check must be performed:

const pokemonContainer = document.querySelector('.pokemon-container');
let pokemonData = [];

async function fetchPokemon(){
    await fetch("https://pokebuildapi.fr/api/v1/pokemon")
        .then((res) => res.json())
        .then((data) => pokemonData = data);

    pokemonDisplay()
}

function pokemonDisplay(){
    pokemonContainer.innerHTML = pokemonData
        .map((pokemon) => 
        
        `
        <div class="card">
        <h2>#${pokemon.id}  ${pokemon.name}</h2>
        <img src="${pokemon.image}" class="pic">
        <img src="${pokemon.apiTypes[0].image}" class="type">` +
        (pokemon.apiTypes[1]?.image ? `<img src="${pokemon.apiTypes[1].image}" class="type">` : '') +
        `<ul>
        <li>PV  ${pokemon.stats.HP}</li>
        <li>Att  ${pokemon.stats.attack}</li>
        <li>Def  ${pokemon.stats.defense}</li>
        </ul>
        </div>
        `
        
        ).join("");
};

window.addEventListener('load', fetchPokemon);

The replacement of IDs with classes was carried out as IDs need to be unique.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using traditional JavaScript, bring in a class from Node.js

I have a mix of files utilizing the Node.js framework and others that I'd like to incorporate without it. When attempting to import a class from my Node files, where module.exports was used, into my JavaScript files, I encounter an error stating "the ...

The longevity of JQuery features

As I work on setting up an on-click callback for an HTML element to make another node visible, I encountered a surprising realization. The following two statements appeared to be equivalent at first glance: $("#title").click($("#content").toggle); $("#tit ...

transferring the parsed JSON document to the recipient, however, it does not adhere to

After calling the API and parsing the JSON data, I now aim to present this parsed JSON in tabular form on the receiving page. Currently, it is being displayed as plain text. The API URL used for testing purposes has been sourced from WIKI to safeguard act ...

Ways to implement a delay in a function?

I'm looking for a way to introduce a delay in my function. Should I enclose the function within a delay function, or is there a different method to ensure that the animation doesn't trigger until 5 seconds after the page has loaded? var textTo ...

What is the best way to retrieve data from a json object using Python?

Within my data frame, there is a column that holds JSON objects labeled as cast_and_crew. I am trying to extract the 'person_name' key value and place it into a separate data frame. You can view the data frame containing the cast_and_crew JSO ...

How can I modify the value of a variable in Vue.js in order to display a Bootstrap alert based on a specific condition?

Apologies in advance if my question seems obvious. As a newcomer to Vue.js, I'm facing a roadblock and could really use some assistance. In my authentication system, I want to display a Bootstrap alert if a user tries to register without entering a u ...

Guide to successfully finish $.get() after submitting a form with jQuery

I'm currently utilizing a third-party shopping cart system that sends a registration form to a .cgi script. My goal is to send the form details to both me and the customer using a jQuery $.get() function call. The $.get method calls a registration.m ...

Add a new sibling item to Angular-UI-tree

I am trying to add a sibling item to a tree when clicked in angular-ui-tree (https://github.com/angular-ui-tree/angular-ui-tree) Here is an example of what I currently have: <item><input value"item A #1"><button>insert under</button& ...

Encountering an SyntaxError with Next.js and Jest: "Import statement cannot be used outside a module"

Currently, I am developing a project with Next.js using TypeScript. For testing purposes, I rely on Jest and React Testing Lib. However, I have encountered an issue where I receive a SyntaxError: Cannot use import statement outside a module for components ...

Steps for generating instances of an HTML page and dynamically adding them to a list on the main page

I have a main HTML page and I need to insert a dynamically generated list from a template in another HTML file that I created. The template for each item in the list is located on a separate HTML page. My goal is to create multiple instances of this HTML ...

When working with Typescript, encountering difficulty in locating or importing modules from a parent directory that is one level above the tsconfig.json file is

My project's directory structure looks like this: Main/project-root/* (tsconfig.json, packages.json, app.ts, etc are located here) Main/shared/* (shared.ts is located here along with other ts files, no packages.json or any other files) Let's ...

What's preventing me from accessing children in three.js group?

Having this particular class declaration class GameManager { constructor() { this._activeObjects = new THREE.Group(); } get randomGeometry() { const geometry = new THREE.BoxGeometry(0.1, 0.1, 0.1); return geometry; } get randomMat ...

Managing communication with a serial port via a web application (PHP, JavaScript) with the assistance of MySQL and Python

Looking for feedback on my current project. I am working on creating a PC application that can communicate with a serial port to send and receive data. The data received by the application can either be requested or unsolicited. To manage the serial por ...

Having trouble fetching information from SharePoint list within specific date range using JavaScript CAML query

When I use CAML JavaScript to retrieve data from a SharePoint list between two dates, I encounter an issue. I am able to retrieve data successfully if the two dates fall within the same month, however, if the dates are in different months, no data is ret ...

What is the method for excluding specific sections of JSON data stored in Postgres when retrieving records with ActiveRecord?

This is a subsequent inquiry related to the following topic: How can I extract specific portions of JSON data stored in Postgres using ActiveRecord? Imagine that there is a model called User, containing a field of type json named settings. Let's con ...

Overflow is causing interference with the scrollY value

I've been attempting to retrieve the scrollY value in my React app, but it seems to be affected by overflow-related issues. Below is the code snippet I used to access the scrollY value: import React from "react"; import { useEffect, use ...

Troubleshooting Listing Errors in Android Using ExpandableListView and JSON Data

Attempting to create an ExpandableListView using JSON parsing, but encountering errors. I have tried to parse JSON data into a single child group without success. If anyone can resolve this issue, it would be greatly appreciated. The project does not con ...

Guide on dynamically importing a module in Next.js from the current file

I am facing a challenge where I have multiple modules of styled components in a file that I need to import dynamically into another file. I recently discovered the method for importing a module, which requires the following code: const Heading = dynamic( ...

How can one activate a function using jQuery and then proceed to activate another function once the first function has finished executing?

My current assignment involves implementing a task using jquery. Upon loading the page, the initial jquery function will be executed. After the successful completion of the first function, it should seamlessly transition to the next function on its own. ...

Finding a character that appears either once or thrice

In my work on JavaScript regex for markdown formatting, I am trying to match instances where a single underscore (_) or asterisk (*) occurs once (at the beginning, end, or surrounded by other characters or whitespace), as well as occurrences of three under ...