retrieve: add elements to an array

I'm having trouble identifying the issue here. I am fetching some json data (using a text file) and trying to push it into an array in the global scope. Even though I iterate over the json and push entries to the array, when I log it out, it appears empty. It seems like a simple mistake, but any help would be greatly appreciated.

let charities = [];
fetch('../mapdata/markers.txt').then(response => {
        if (response.ok) {
            return response.json();
        }
        throw new Error('Network response error.');
    })
    .then(charData => {
        console.log(`inside: ${JSON.stringify(charData, null, 2)}`);
        charData.map(entry => {
            return charities.push(entry);
        });
    })
    .catch(error => {
        console.log('There has been a problem: ', error.message);
    });
console.log(`outside: ${JSON.stringify(charities, null, 2)}`);

As I type this, I can't help but wonder if this might be an asynchronous issue...

Answer №1

When performing an asynchronous operation and trying to access the data [] immediately after initiating the asynchronous operation, it will always be empty.

Instead of that approach, move the console.log(

outside: ${JSON.stringify(charities, null, 2)}
); statement inside the second then() function. This way, the data will be printed only after it has been added to the array.

.then(charData => {
    console.log(`inside: ${JSON.stringify(charData, null, 2)}`);
    charData.map(entry => {
        return charities.push(entry);
    });

    console.log(outside: ${JSON.stringify(charities, null, 2)});
})

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

Generate HTML content based on the permissions from a REST API

I have a frontend that renders based on user permissions from a REST API. These permissions could include deleting users, creating users, adding users to workflows, and more. Most of these permissions are managed by an administrator. So my question is: H ...

Preventing JavaScript from refreshing the page when using location.replace for the second time with the identical URL

I've encountered an issue while using location.replace to reload a page that relies on GET variables for displaying a success message. The problem arises when the URL specified in the location.replace call is identical to the current one, causing the ...

Discover the ins and outs of integrating YAML front matter into your destination directory path

I am looking to customize the path of my blog posts to include a fancy date format like /blog/2013/09/17 so that the links from my previous octopress blog remain intact. Within the YAML front matter on each markdown page, I have included the date informat ...

I am looking to add some flair to my ID "checkimg" using JavaScript

JavaScript if ((valid1 && valid2 && valid3 & valid4 && valid5 && valid6 && valid7 && valid8)==1) { // include an image in the specified ID. document.formElem.next1.disabled=false; } else { docume ...

Ways to retrieve the chosen option from a dropdown menu within an AngularJS controller

I have a drop down (combo box) in my application that is populated with values from a JSON array object. Can someone please explain how to retrieve the selected value from the drop down in an AngularJS controller? Appreciate the help. ...

Encountering an issue with a class component stating that "this.setState is not a function

I am currently learning React JS and encountered an error when calling my first API in React. I keep getting the message "Unhandled Rejection (TypeError): this.setState is not a function." I have been trying to troubleshoot this issue on my own but haven ...

Error message: Unable to locate module when using a variable to import an image in React

I've encountered an issue with my React code that I can't seem to figure out. I am integrating the Accuweather API and trying to display the weather icon on my app. Initially, everything seemed to be working fine as I constructed the image path l ...

Struggling to get Ajax to function on IE8 with dropdowns, while other browsers are working perfectly fine

My AJAX code functions properly in most browsers, however, it is not performing well in IE. While it successfully creates an XMLHTTPRequest object, the data retrieved from my PHP script is only returning an empty list! Check out my JavaScript code: < ...

How to append double zeros to a number in Material UI Data Grid

I'm currently working on a React.js application that utilizes the DataGrid component from the Material UI (MUI) library to display data. My challenge lies in formatting full numbers with trailing zeroes for better clarity. For example, displaying 625 ...

Leveraging hapi-auth-basic

I attempted to incorporate a basic authentication strategy following a tutorial I stumbled upon. Here is the setup of my server.js file. 'use strict'; const Hapi=require('hapi'); const sequelize = require('sequelize'); c ...

Having issues when dynamically adding options to a multiselect dropdown

I'm working on dynamically adding options to a multiselect using AJAX: <select size='2' name="CraftCode" id=@ccrf class="form-control js-select manualentrydd" ></select> $.ajax({ type: "GET", url: "GetCraftCodes", data: ...

What is the best way to query the ng-model table using xpath in Selenium with Java?

I'm having trouble finding a table from DOCTYPE Html using xpath or className in Selenium/java. I can't seem to locate the locator. How can I retrieve the table using selenium java? Neither of the following paths are effective. You can view a sc ...

Difficulty encountered while extracting information from JSON output

I am new to working with JSON. The more I work with it, the more I find myself liking it. Currently, I have an output that resembles the following structure: [ { "product": { "id": "6", "category": "Books", ...

Exploring the world of unit testing with Jest in Strapi version 4

In my quest to conduct unit tests using Jest for the recently released version 4 of Strapi, I have encountered some challenges. The previous guide for unit testing no longer functions as expected following the latest documentation updates. Despite my effor ...

Placing jQuery in the lower part of my HTML templates lacks adaptability

Lately, I've been optimizing my templates by placing the jQuery code link at the end of the template files to ensure fast page load speeds. Along with that, I have specific javascript modules reserved for certain pages that are included within the con ...

Saving the index.html file to disk when the button is clicked

Is there a way to export the current HTML page to a file? I have attempted to achieve this using the following code, but it only works when the page is loaded and not with a button click. <?php // Start buffering // ob_start(); ?> <?php file_pu ...

The function XmlHttpRequest getResponseHeaders() is not providing a complete list of all headers

Has anyone encountered the issue where jQuery's xhr method, getAllResponseHeaders, only displays the "Content-Type" header when trying to retrieve response headers from an ajax request? Below are the response headers: Access-Control-Allow-Credentia ...

Expanding the Element prototype with TypeScript

Is there a corresponding TypeScript code to achieve the same functionality as the provided JavaScript snippet below? I am looking to extend the prototype of the HTML DOM element, but I'm struggling to write TypeScript code that accomplishes this with ...

Page load triggers background color shift

Here is the structure of my markup: <div class="authentication"> <div class="form-inputs"></div> </div> My goal is to have the color of the authentication section slide down from top to bottom when the page loads. Initially, the ...

What is the process for entering a value into mysql based on the date?

Seeking assistance with a specific coding challenge. The task at hand involves inputting a date, such as '2018-05-08', and based on the user's input, storing the value in different columns of a database table. For instance, if the date is &a ...