Having difficulty using the forEach() method to loop through the array generated by my API

During my troubleshooting process with console.log/debugger, I discovered that I am encountering an issue when attempting to iterate over the API generated array in the addListItem function's forEach method call.

Interestingly, the pokemonNameList array does get populated during the forEach iteration in the loadList function.

I'm struggling to identify where I might be going wrong. Any help or insights would be greatly appreciated!

const apiUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=15';
const pokemonNameList = [];

function getAll() {
    return pokemonNameList;
  }

function add(pokemon) {
    if (typeof pokemon === 'object') {
      pokemonNameList.push(pokemon);
    }
  }

function loadList() {
    return fetch(apiUrl)
      .then((response) => response.json())
      .then((data) => {
        data.results.forEach((item) => {
          fetch(item.url)
            .then((response) => response.json())
            .then((inneritem) => {
              const pokemon = {
                name: inneritem.name,
                height: inneritem.height,
                weight: inneritem.weight
              };
              add(pokemon);
              console.log(pokemonNameList);// The array is visible here
            });
        });
      })
      .then(() => {
        console.log(pokemonNameList);
      })
      .catch((e) => {
        console.error(e);
      });
  }

function addListItem(pokemon) {
    console.log('It seems like this console log is not displaying');//This does not show up
    const card = document.createElement('li');
    const cardbody = document.createElement('div');
    const name = document.createElement('h1');

    card.classList.add('card');
    cardbody.classList.add('card-body');
    name.classList.add('card-title');
    name.innerText = pokemon.name;

    cardbody.appendChild(name);
    card.appendChild(cardbody);
    pokemonList.appendChild(card); // Assuming there is a variable called "pokemonList"
  }

loadList()
  .then(() => {
    getAll().forEach((item) => {
      console.log('Hello from inside the forEach');//I cannot see this
      addListItem(item);
    });
  })
  .catch((e) => {
    console.error(e);
  });

Answer №1

One issue arises when the inner fetch(item.url) calls are not being waited for, causing getAll to be called before any items have been pushed.

To address this, you can switch from using forEach to map, return the promise, and implement a promise.all like so:

function loadList() {
    return fetch(apiUrl)
      .then((response) => response.json())
      .then((data) => {
        return Promise.all(data.results.map((item) => {
          return fetch(item.url)
  ...

Answer №2

I have already implemented all the necessary functions up to the point where you identified the error

const pokemonNameList = []; // Array to store Pokemon names
const apiUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=15'; // URL for PokeAPI
// To avoid duplicates when calling loadList multiple times, I use the index from the response to update the correct element in the array
const add = (pokemon, index) => pokemonNameList[index] = (pokemon);
const getAll = _ => pokemonNameList; // Short arrow function to return pokemonNameList

async function loadList() {
    const response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=5');
    const result_1 = await response.json();

    Promise.all(result_1.results.map((item, index) => fetch(item.url).then(response_1 => response_1.json()).then(({
        name,
        height,
        weight
    }) => add({
        name,
        height,
        weight
    }, index)))).then(() => getAll().forEach(pokemon => console.log(pokemon)));
}

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

What is the method for modifying the input element within a TextField component from MUI?

I have TextField elements in my application that appear to be too large. Upon inspection, I noticed that the input element within them has default padding that is too big.https://i.stack.imgur.com/C13hj.png My query is regarding how to adjust the styling ...

CSS guidelines for layering shapes and divs

Currently, I am in the process of developing a screenshot application to enhance my understanding of HTML, CSS, and Electron. One of the key features I have implemented is a toggleable overlay consisting of a 0.25 opacity transparent box that covers the en ...

Refresh element once AJAX call is completed successfully

Issue Despite a successful AJAX request, I am encountering difficulties updating an element on the webpage. JavaScript Code $(function() { $(".upvote").click(function() { var id = $(this).parent().find("input").val(); $.ajax( ...

Issue with InversifyJS @multiInject: receiving an error stating "ServiceIdentifier has an ambiguous match"

Having an issue with inversifyJs while trying to implement dependency injection in my TypeScript project. Specifically, when using the @multiInject decorator, I keep receiving the error "Ambiguous match found for serviceIdentifier". I've been referenc ...

The :first selector examines the parent's parent as a reference point, rather than the immediate

I am facing a challenge with shuffling large elements within my layout because of floating them and attempting to display them. Specifically, the elements with the class .gallery-large always need to be the first child inside the .item container. There are ...

Using jQuery to alter hover color using a dynamic color picker

I'm looking to update the hover color using a color picker tool. Here are the methods I've attempted: // Initial Attempt $("input[type=color]").change(function(e) { var selectedColor = e.target.value; // $("body").css("background-color ...

What is the best way to display data in a React application depending on a boolean value?

Being new to React and JavaScript, I am currently struggling with boolean logic. I have a function called Profile which includes two constant methods that each return different data. function Profile(props) { const returnNormalProfile() const return ...

Please provide either a render prop, a render function as children, or a component prop to the Field(auto) component

While working on my project and implementing an Auto complete feature using final-form, I encountered the following error: Must specify either a render prop, a render function as children, or a component prop to Field(auto) In order to resolve this issue ...

Having trouble transmitting JSON data to an Express server through the browser

I have set up two servers: the first one is for frontend (localhost:7200), and the second one is for backend (localhost:7300). There is a test request made by the frontend to the backend on the route '/test'. The issue arises when I attempt to s ...

Capturing mouse coordinates from hover events in Highcharts Gantt using the highcharts-react library

Currently, I am utilizing the official React highcharts wrapper to create a Gantt chart. My goal is to obtain precise mouse coordinates from a mouse-over event and utilize them for a custom tooltip. For instance: https://stackblitz.com/edit/react-c5mivs ...

Froala text area is unexpectedly visible when I attempt to cover it with a partially see-through mask

The website I'm currently developing features a semi-transparent overlay that dims the screen with a light-colored message displayed on top. This overlay and message are shown whenever there is a background process running. Everything was running smoo ...

What is the technique for arranging the display of a component in React?

Is there a way to dynamically render a component in my react-app at a specific date and time, like 6.00PM on October 27, 2022? I want to release a form for signing up starting from that exact moment. The timestamp information will be stored in my database ...

Is it possible to utilize onclick for various table cells in jQuery?

I have a situation where I need to loop through dates and display table content accordingly. Could someone please assist me in figuring out how to do this? index.html.erb <% @batches.each do |batch| %> <tr> **<td class = "pie" id ...

Is there a way to continue a failed fetch request?

I am curious about the possibility of resuming an incomplete fetch request if it fails due to a non-code-related issue, like a lost network connection. In one of my current projects, we send a large download via AJAX to the client after they log in. This ...

Switching background images for DIVs when links are rolled over

Having trouble changing the background image of a div when a user hovers over a link. Any ideas on what might be causing this issue? <style> #divToSwap { background-image: url(black.jpg); height: 150px; width: 150px; } </style> &l ...

AngularJS: Importing a parent directive within a child directive

Take a look at this Plunk example to understand better. I'm attempting to create a test scenario for accessing complex directives, but I encounter an error when trying to call a method from the parent directive: Parent Directive app.directive(&apos ...

Struggling to find the right strategy for obtaining real-time data while implementing customized filters

After spending a week scratching my head and experimenting with different approaches, I'm hoping to find some help here... I am working on an application that needs to provide real-time data to the client. I initially considered using Server-Sent-Eve ...

Having trouble changing my array state in react?

I'm having trouble understanding why my React state isn't updating with the following code: state = { popUpMessages:[] } popUpMessage(id,name) { console.log("id ",id,"name ",name) const addUserObject = { id, name }; const new ...

Resize the main container to fit the floated elements

I've been working on constructing a family tree, and the last part of the functionality is proving to be quite challenging for me. My family tree consists of list elements that are all floated to the left. Currently, when the tree expands beyond the ...

Slider Volume with jQuery

Struggling to find a solution for this issue. Seeking some assistance. My goal is to create a basic volume slider. So, the orange section represents my volume slider. This is the jQuery code I am using: var mouseIsDown = false; $("#volSlider").on("mou ...