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

Creating element modules in EJS

After building experience with React, I am now faced with the task of using ejs in my current project. Specifically, I need to return multiple radio elements. My attempt at achieving this was through the following code: <% const renderRadios = (value, ...

Arrange a collection of objects based on various nested properties

I am faced with the challenge of managing an array of objects representing different tasks, each categorized by primary and secondary categories. let tasks = [ { id: 1, name: 'Cleanup desk', primary_category: { id: 1, na ...

Attempting to showcase information in React

Having recently delved into React, I am attempting to display data (within a bootstrap modal) from MongoDB to React using an axios ajax request. Postman indicates everything is correct. However, React throws an error stating "TypeError: this.state.reviews. ...

Struggling to display the Three.js LightMap?

I'm having trouble getting the lightMap to show on my mesh. Here's the code I'm using: loader.load('model.ctm', function (geometry) { var lm = THREE.ImageUtils.loadTexture('lm.jpg'); var m = THREE.ImageUtils.loadT ...

Troubleshoot: Dropdown menu in Materialize not functioning (menu fails to drop down

I am currently incorporating Materialize to create a dropdown button in my navigation bar. However, I am facing an issue where nothing happens when the button is clicked. Here is a snippet of my code: <head> <meta charset="UTF-8"> <!-- ...

Is it possible to utilize a conditional statement in my EJS document to determine a directory path within my Node.js and Express application?

Just starting out with EJS and I'm trying to create a conditional statement. Basically, what I want is if I am on a specific directory path, then replace a link in my navigation bar. <% let url = window.document.URL; if(!url.includes(&a ...

display rails view using ajax

I have developed a new form that I would like to render using ajax in case it fails validations. In my controller, the code looks like this: def create event = CEvent.new(params[:c_event]) respond_to do |format| if event.save format.html { ...

Explore the world of threejs with a sphere adorned with cube bumps

Currently, I am navigating through the internet in search of a solution for my problem. The example I came across is quite impressive, take a look: . My dilemma lies in converting these squares into CSS cubes while ensuring that they do not get cut off by ...

JavaScript implementation of Ancient Egyptian Multiplication using PHP code

Let's dive into the algorithm. If we have two integers, A and B (remember, only integers), that need to be multiplied, here is how it works: we continuously multiply A by 2 and divide B by 2 until B cannot be divided any further, or in other words, un ...

Center both vertically and horizontally in Bootstrap UI Modal

I'm attempting to create a Bootstrap UI Modal that is centered both vertically and horizontally. While I found this solution that successfully centers the modal vertically, it loses its horizontal centering when applied to my own template with 800px ...

Guide on invoking a node.js function from an express-rendered ejs page

My express server currently has a button that triggers a POST request to activate a function in my node.js server. Instead of using a traditional POST request, I am interested in implementing something like AJAX so that the page doesn't reload. Is th ...

Eliminating the use of undefined values in JavaScript output

When the following script is run in a JavaScript environment like Node.js, the output is as follows: undefined 0 1 2 3 4 The Script: for(var i=0;i<5;i++){ var a = function (i) { setTimeout(function () { console.log(i); ...

"ModuleNotFound" error occurred when attempting to utilize Netlify lambda functions with external dependencies

https://i.stack.imgur.com/vVmky.jpg I'm currently exploring the capabilities of Netlify, specifically its lambda function feature for running a node function with dependencies. Following a tutorial from CSS-Tricks, my functions/submission-created.js ...

Transmit an array using a GET Request

I am currently working on a project where I need to make a GET request from JavaScript to Python and pass a 2D array. Here is an example of the array: [["one", "two"],["foo", "bar"]] However, I am facing issues with passing this array correctly. In my Ja ...

What is the most efficient way to calculate the total sum of all product amounts without using Jquery?

I am working with a dynamic table where data is inserted and the total of each product is calculated by multiplying the price by the quantity. What I need now is to get the sum of all the totals for each product. You can see how the table looks here: htt ...

Struggling to locate a route for the React styled components image

I'm having trouble locating the correct path for the image in my React styled components. I believe the path is correct, but could the issue be related to styled-components? Check it out here import styled from "styled-components"; export defaul ...

Loading state with suggestions from autocomplete feature on React

In my current project, I have a component that consists of input fields and a button. The button is set to be disabled until the correct values are entered in the input fields. Everything works as expected, but there's an issue with Chrome auto-fillin ...

Guide to receiving dynamic argument variables in jQuery using $.get

I am currently working on developing an Ajax function call. In this function, the argument q will be dynamically defined, and the $.get method will return either true or false based on the data received from the Ajax call. <a href="any.php" class ...

Obtain the content of a clicked item on the following page using NextJs

I am currently working on a nextjs app that displays a list of 10 movies on the homepage, each with a Button / Link that leads to a specific page for that movie where all its content is shown. Initially, I tried adding the movie id to the Link like this: ...

Prevent textArea from reducing empty spaces

I am facing an issue with my TextEdit application set to Plain Text mode. When I copy and paste text from TextEdit into a textarea within an HTML form, the multiple spaces get shrunk. How can I prevent the textarea from altering the spacing in the text? T ...