retrieve a value from an eventListener embedded within a forof iteration

How do I pass the coin object returned from the displayCurrencies function to the getCoinId function as a parameter for making an API call to retrieve specific coin data?

This is the function created to return the value:

let returnID = (value) => {
  return value;
};

This is the function where I want to return the coin from:

let displayCurrencies = async () => {
  let coinsContainer = document.querySelector(`.coins`);
  try {
    let coins = await getData();
    let coinsArray = [];
    let coinElement;
    for (const coin of coins) {
      coinElement = coin;

      if (coinsArray.length > 20) {
        break;
      }
      coinsArray.push(coin);
      // create Nodes
      let coinDisplay = createElement(`li`, `coin`);
      let coinSymbolElement = createElement(`p`, `coinSymbol`);
      let coinIDElement = createElement(`p`, `coinID`);
      // set Values
      coinSymbolElement.innerHTML = coin.symbol;
      coinIDElement.innerHTML = coin.id;

      // append
      coinDisplay.append(coinSymbolElement, coinIDElement);
      coinsContainer.appendChild(coinDisplay);

      coinDisplay.addEventListener(`click`, () => {
        openModal();
        returnID(coin);
      });
    }
    let returnCoin = returnID
    coinDisplay.addEventListener(`click`, () => {
    console.log(returnCoin);
    });

    console.log(returnCoin);
    
  } catch (error) {
    console.log(error);
  }
};

And finally, this is the function in which I want to use the returned value:

displayCurrencies();
let getCoinId = async () => {
  let coinID = await displayCurrencies();
  let currencyData = `https://api.coingecko.com/api/v3/coins/${coinID}`;
  let responseData = await fetch(currencyData);
  let dataOfCoins = await responseData.json();
  console.log(dataOfCoins);
};

Answer №1

To enable the functionality for each element, you can implement an onclick event where upon execution, the getCoinID function is triggered with the coinID passed as an argument.

Here's a straightforward demonstration:

<ul class="coins">
</ul>

<script>
    function addOnClick() {
        let coinsContainer = document.querySelector('.coins');
        let coins = [
            { id: 1, symbol: 'bitcoin' },
            { id: 3, symbol: 'brazil-fan-token' },
            { id: 4, symbol: 'celo-euro' },
        ]

        for (const coin of coins) {
            let coinDisplay = document.createElement('li')
            let coinSymbolElement = document.createElement('p')
            let coinIDElement = document.createElement('p')

            coinSymbolElement.innerHTML = coin.symbol
            coinIDElement.innerHTML = coin.id

            coinDisplay.appendChild(coinIDElement)
            coinDisplay.appendChild(coinSymbolElement)

            coinsContainer.appendChild(coinDisplay)

            coinDisplay.addEventListener('click', () => {
                getCoinID(coin.symbol)
            })
        }
    }

    async function getCoinID(coinID) {
        let currencyData = `https://api.coingecko.com/api/v3/coins/${coinID}`
        let responseData = await fetch(currencyData)
        let dataOfCoins = await responseData.json()
        console.log(dataOfCoins)
    }

    addOnClick()
</script>

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

An effective method for binding items permanently while still being able to update the entire selection

Imagine a scenario where a list of 1000 items is displayed using infinite scrolling. Each item on the list includes a person's firstName, lastName, and mood for simplicity. Initially, I didn't want to constantly listen for updates. Fortunatel ...

Swapping out existing HTML content with discovered content

My attempt to replace a specific content in the HTML body is illustrated in the code snippet below. var fontReplacer = $("body").html().replace(/\{fontsize:(.*?)\}(.*?(({fontsize\})|$)/g,'<span style="font-size:$1px">$2</spa ...

Unlocking the power of RXJS by de-nesting subscriptions

Trying to resolve the nested subscription issue has become a time-consuming puzzle. I've experimented with mergeMap, flatMap, and switchMap without success. Unfortunately, the examples I've come across don't quite fit my needs, leaving me wi ...

How can I retrieve documents with a specific count using MongoDB aggregation?

I've been working on this code for the past 24 hours trying to fetch all records from the last 24 hours along with their total count. db.getCollection("COLLECTION_NAME").find({"createdAt":{$gt:new Date(Date.now() - 24*60*60 * 1000)}}) ...

What causes Angular to redirect to the route but display the incorrect view?

There is a fundamental issue I have encountered while working with routes: I have multiple routes defined If the user is not authenticated, they are redirected to the login page The problem lies in the fact that, on the initial display of the web app, t ...

What is the best way to include a PHP mail file in an Angular project?

I have recently developed a single-page application using Angular that features a contact form. To handle the functionality of this contact form, I opted to use the PHP mail function. The PHP file responsible for handling the form submissions is located wi ...

CoffeeScript's alert feature appears to be malfunctioning

After stumbling upon CoffeeScript in a blog post, I was excited to try it out. My first attempt at using it involved this code snippet: alert "Hello CoffeeScript!" Unfortunately, it didn't work as expected and produced the following error message: ...

React does not support custom hooks as a function

Every time I attempt to invoke a function from my custom hook, an error message pops up on the screen upon loading stating that setAuth is not recognized as a function. useAuth.js import { useContext } from "react"; import AuthContext from " ...

Questions regarding prototype-based programming in Javascript

I am interested in achieving the following using Javascript: function A(){ this.B = function() { ... }; this.C = function() { <<I need to call B() here>> } ; }; I came across a method of method overloading, but I am curious to know ...

Trouble arises when trying to create an auto suggest text box using PHP and Javascript

I've been working on creating a basic auto-suggest input feature that connects to a MySql database to retrieve data. However, I'm facing a particular issue where when I enter the name of an object that I know exists in the database, the input bar ...

Creating a webpage using webkit technology

As someone new to web development, I am eager to create a website that is user-friendly on both desktops and mobile devices. Recently, I stumbled upon a site with impeccable design and functionality using what appeared to be "screen webkit". I'm curi ...

The Angular 2 Router's navigation functionality seems to be malfunctioning within a service

Currently, I am facing an issue with using Angular2 Router.navigate as it is not functioning as expected. import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { Router } from '@angular/ ...

AngularJS grid designed to emulate the functionalities of a spreadsheet

I have been facing challenges with Angular while attempting to recreate a spreadsheet layout in HTML using ng-repeat. Despite extensive research, I have not found a solution. My goal is to display data in a table format as shown below: <table> & ...

Numerous scripts available for achieving a responsive layout using (window).resize event

I am currently in the process of creating a one-page website with a responsive design. On smaller screens, I have implemented an animated scroll plugin to navigate between content divs, while on larger screens, I am using a plugin to toggle the visibility ...

What methods could I use to prevent the WYSIWYG buttons from automatically linking?

I've been working on creating an editor but I'm facing a small issue. Every time I click on a button (such as bold or italic), it follows a link instead of performing the desired action. Here's a snippet of what I've tried so far: fu ...

Can .NET MVC be used to host vue.js static files?

I recently received a sample Vue app created using vue-cli, which generates static files when the npm run build command is executed. Normally, these files are served by a server from node.js. However, I am curious to know if it's possible to serve th ...

Using an array to suggest possible completions for input values

Can we dynamically insert data into values in tabulator using two arrays instead of hard coding user names? The first array would store the usernames, while the second array would store the actual names of the users. {title:"Approver", field:"Approver", ...

transferring data from a form with a binary image file to store in an SQL server

I am aiming to create a form where users can upload an image along with some data fields. Currently, I can only get either the image or the data fields to work separately. The following code allows me to upload an image to my SQL database as binary data. I ...

Ending asynchronous tasks running concurrently

Currently, I am attempting to iterate through an array of objects using a foreach loop. For each object, I would like to invoke a function that makes a request to fetch a file and then unzips it with zlib, but this needs to be done one at a time due to the ...

Tips for eliminating null values from a JavaScript object

I am currently facing an issue with a JavaScript object that consists of two arrays. At times, one of the arrays might be empty. I am attempting to iterate through the object using a recursive function, but I want to exclude any empty arrays or strings fro ...