Execute the function numerous times that is associated with an asynchronous function in JavaScript

I am currently working on two functions: one is asynchronous as it fetches data from a CSV file, and the other function renders a list of cities. The CSV file contains information about shops located in various cities. My goal is to display a list of cities on an HTML page and dynamically append the corresponding shops when a specific city is clicked. However, I am facing an issue where I cannot render the list for a different city if I have already done so for another city.

let arr; 
let shops = [];
let cities = [];


async function getData() {
  let response = await fetch('list.csv', {credentials: 'include'});
  const data = await response.text();
  arr = data.split('\n');
    
  let headers = arr[0].split(';');
  for(let i = 1; i < arr.length; i++) {
      let datas = arr[i].split(';');
      let obj = {};
      for(let j = 0; j < datas.length; j++) {
        obj[headers[j]] = datas[j].trim();
      }
    shops.push(obj);
  }


  //group cities
  for (let i = 0; i < shops.length; i++) {
        cities.push(shops[i].IC_GROUP0);
  }

  renderLists();
}

getData();

function renderLists() {

  for (let i = 0; i < cities.length; i++) {
    let listOfCities = document.createElement("LI");
    town = document.createTextNode(cities[i]);
    listOfCities.appendChild(town);
    listOfCities.setAttribute("id", cities[i]);
    document.getElementById("list").appendChild(listOfCities); 
  }

  for (let i = 0; i < cities.length; i++) {
    document.getElementById(cities[i]).onclick = function makeAList() {
      shops = shops.filter(item => item.IC_GROUP0 == cities[i]);

      //addresses
      for (let m = 0; m < shops.length; m++) {
        let nodeAddress = document.createElement("P");

        //list of shops to HTML
        let address = document.createTextNode(shops[m].IP_PROP303);

        nodeAddress.appendChild(address);

        document.getElementById(cities[i]).appendChild(nodeAddress);
      }
    }
  }
}

Answer №1

The issue arose right after the "onclick" function was implemented. The array 'shops' underwent a rewrite. To rectify this, I employed the code snippet

let shopsFiltered = shops.filter(item => item.IC_GROUP0 == cities[i]);
. Subsequently, I made a simple adjustment in every rendering instance by replacing shops[m]... with shopsFiltered[m]....

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

Activating view loading in AngularJS through child window authentication (OAuth)

I have tried implementing OAuth in AngularJS using Hello.js following what I believe is the best practice. However, I am encountering some issues with my current approach as described below: After injecting Hello.js into Angular and setting up the OAuth p ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

Troubleshooting Issue with jQuery replaceWith in Loop

Trying to make it so that when the update button is clicked, the text on the left side becomes an input box: Click the update button and the text on the left will be an input box However, instead of just one input box appearing, all the text on the left s ...

What are the appropriate scenarios to utilize the declare keyword in TypeScript?

What is the necessity of using declare in TypeScript for declaring variables and functions, and when is it not required? For instance, why use declare var foo: number; when let foo: number; seems to achieve the same result (declaring a variable named ...

Utilizing the array result obtained from the fetch function

Seeking assistance with a coding issue. I am puzzled as to why I am unable to utilize the data returned from an API call outside of its function, even though there are no errors occurring. The fetchUser function successfully retrieves the data from the API ...

What is the process for obtaining a JSON result after completing an upload?

I recently started working with the razor view engine and I have encountered a situation where I need to upload an image using the Change event of an image browser. The jQuery function for this task is as follows: $("#billUpload").change(function (){ ...

Tips for passing parameters in the $http GET request to transmit information from a dropdown menu using AngularJS

In the modal window I have for creating a new object, there are three forms: 1) a simple input to create "Name"; 2) A dropdown with "Types"; 3) A dropdown with "Ids". The issue arises when trying to send the data after filling out all the forms. An error o ...

The scrollIntoView function is not functioning as expected

Having an issue with my function called scrollIntoView. It just refuses to work :( Take a look at the code below: HTML <section class="page_mission"> <div class="page_mission_text"> <div class="scroll-animations"> <di ...

The button is effectively disabled for a few seconds as needed, but unfortunately, the form cannot be submitted again using that button

The button is disabled for a specific duration as required, but the form does not get submitted through that button again. Below is the script code written in the head tag $(document).ready(function () { $('.myform').on('submit', ...

Is there a way to identify the moment when a dynamically added element has finished loading?

Edit: I've included Handlebar template loading in my code now. I've been attempting to identify when an element that has been dynamically added (from a handlebars template) finishes loading, but unfortunately, the event doesn't seem to trig ...

javascript dynamic content remains unaffected by ajax call

I'm a beginner with javascript and I am using a PHP variable to create links dynamically. Here is an example of how the variable is set: $addlink = '<button class="blueBtn btnSmall" id="current'.$product_id.'" onClick=addcart(' ...

Using jQuery validation to verify that a minimum of one radio button holds a true value

I have a form with two questions. The first question asks if the product value exceeds a certain fixed amount, and the second question asks if the product value is below that fixed amount. Upon submitting the form, validation should ensure that at least on ...

The componentDidMount function is not initializing the state

I am trying to access the references from the render function and then set them to the state. Below is my code snippet: class App extends Component { constructor(props) { super(); this.arr = this.generateTimelineArray(); ...

Learn how to utilize ng2-file-upload in Angular for uploading .ply files effortlessly!

I'm currently working on uploading various files using ng2-file-upload. I've been successful in uploading different file types like png and jpg, but I'm facing an issue with the .ply file extension. Can someone guide me on how to upload a fi ...

Oops, it seems like there is a TypeError with the function window.initMap in Google Maps

For the past week, I have been struggling to update my marks on Google Maps while using AJAX in an HTML page. My controller fetches data from the database and sends it back, but now I am encountering the following error: TypeError: window.initMap is not a ...

What is the process for generating an alert box with protractor?

While conducting tests, I am attempting to trigger an alert pop-up box when transitioning my environment from testing to production while running scripts in Protractor. Can someone assist me with this? ...

Dynamically loading an AngularJS controller

I am faced with the challenge of integrating an Angular app with dynamically loaded controllers into an existing webpage. Below is a code snippet where I have attempted to achieve this based on my understanding of the API and some research: // Create mod ...

Issues arise when attempting to transfer strings through ajax to a Node.js server that is utilizing express.js

On my website, I am encountering a problem where certain characters are being lost when I send strings to my Node.js server. // Client: microAjax("/foo?test="+encodeURI("this is ++ a test"), function callback(){}); // Server: app.get('/foo',fun ...

How can we dynamically render a component in React using an object?

Hey everyone, I'm facing an issue. I would like to render a list that includes a title and an icon, and I want to do it dynamically using the map method. Here is the object from the backend API (there are more than 2 :D) // icons are Material UI Ic ...

Having trouble with making a POST request in Node.js using Express.js and Body-parser?

Just starting out with nodejs and currently in the learning phase. I've encountered an issue where my POST request is not functioning as expected. I set up a basic html form to practice using both GET and POST requests. Surprisingly, the GET request w ...