Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined.

Here is the code snippet in question:

  const temp = [];
  const reference = firestore.collection("users").doc(user?.uid);
  firestore
    .collection("countries")
    .get()
    .then((result) => {
      result.forEach((item) => {
        temp.push(item.data());
      });
    });
  console.log(temp); //works
  console.log(temp[0]); //does not work

The console displays the following results:

https://i.stack.imgur.com/STV4G.png

Upon observation, it seems that the resulting array doesn't match the expected format, such as (3) [{...}, {...}, {...}], instead showing just [].

If anyone can provide insight into why this issue is occurring, it would be greatly appreciated. Thanks!

Answer №1

The main issue at hand stems from the combination of asynchronous and synchronous code within your script. To elaborate,

firestore.collection("countrys").get()
returns a promise.

To properly access the data it retrieves, you must handle it within the .then() method.

firestore
  .collection("countrys")
  .get()
  .then((querySnapshot) => {
    const tmp = [];
    querySnapshot.forEach((doc) => {
      tmp.push(doc.data());
    });
    console.log(tmp);
    console.log(tmp[0]);
  });

I recommend delving further into resources on promises to enhance your understanding.

Answer №2

Executing the console.log(temp) will happen prior to running the

x.forEach((y) => {
    tmp.push(y.data());
 }); 

portion of code.

To ensure that the console log is successful, you must append another .then method after the initial one to execute when the promise resolves.

This concept is part of JavaScript's event loop mechanism.

I suggest diving deeper into this topic by visiting:

For further understanding of promises, check out:

https://web.dev/promises/

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

Is it possible to make a Venmo API call from the client side without worrying about Access-Control-Allow

Currently, I am developing a small web application using Ember.js and Firebase. At the moment, I do not have a framework in place. My goal is to leverage Venmo's OAuth and API to retrieve usernames, emails, and friends' information. So far, I hav ...

PhoneGap switches up the error type with each consecutive run

Why does PhoneGap change errors after every time it is compiled? Sometimes it runs without any issues, but then the same code throws strange errors like parse error or function not found, even though no changes were made to the code. Here is the code that ...

Unable to compile relative path of threejs using browserify and babel

As a newcomer to babel and browserify, I encountered an issue while trying to transpile with browserify and babel. After installing the threejs package and adding the following import: import * as THREE from 'three' Everything worked fine when t ...

When using JSON.stringify on a map object, it returns an empty result

var map1= new Map(); map1.set("one",1); var map2 = new Map(); map2.set("two",2); concatMap = {}; concatMap['one']= map1; concatMap['two']= map2; JSON.stringify(concatMap); //outputs : "{"one":{},"two":{}}" I als ...

Axios is not properly executing the post request

While attempting to submit data using axios in NodeJS and ReactJS, I encountered the following errors: Here is the code I used for posting: axios({ method: 'post', url: '/api/signup', data: { username: this.state. ...

Interacting with an ASP.NET Core API from a React application, both of which are containerized

My containerized app is a mix of React, ASP.NET Core, Keycloak, and Nginx. I want to restrict access to the API port only within the containers' network, not over the internet. However, I'm encountering issues making API calls from my React app ...

Challenges encountered when setting up a containerized application using Next.js, Flask, and PostgreSQL

Challenge: I've been encountering difficulties in containerizing my application that includes a Next.js frontend, Flask backend, and PostgreSQL database. The primary issue I'm facing currently is the incorrect loading of my PostgreSQL schema. St ...

Can the column order in the material table be saved to a database in order to maintain its consistency?

One of my goals is to enable users to drag the columns on the material table and maintain that state persistently. Despite being able to retrieve and save the states of my columns along with their orders, I am encountering issues when attempting to render ...

Exploring the focus() method of refs in Vue 3

I'm struggling to comprehend why my straightforward test case keeps failing. As I delve into the world of testing in Vue, I've created a simple test where the element.focus() is triggered onMount(() => /* see implementation ...

What steps should I take to correct the color selection of a button that has been pressed down

Here is the code snippet that I am currently working with: HTTP: <label class="instructions" for="hidden_x"> Insert X: </label> <button type="button" class="button" name="button_x" value="1" id="x_1" onclick="document.getElementById(' ...

Revise the text while keeping the column content unchanged

Is it possible to change the text in a column without affecting the image using Jquery? Can this be achieved solely with Jquery without any modifications to the HTML code? Check out the demo $(".jsNoWrap").text("Change text"); <script src="https://a ...

Avoiding page refresh while utilizing the ng5-slider component in Angular

I am currently working with an ng5-slider that has a customizable range from 0 to 1000. However, I have encountered an issue when adjusting the slider at the bottom of the page - it refreshes and automatically takes me back to the top of the page. I would ...

Navigating a collection of objects in JavaScript: A step-by-step guide

My data consists of objects in an array with the following structure: [{\"user\":\"mcnewsmcfc\",\"num\":11},{\"user\":\"ManCityFNH\",\"num\":7}]; To clean up the array, I'm using this code: ...

The console logs indicate success for every call, but unfortunately Twitter is not displaying the retweets

Hey there! I'm having some trouble with calling a function and it's not working as expected. var T = new Twit(config); var retweet = function() { T.get('search/tweets', {q:'#python3, #nodejs, python3, nodejs,', count :5 }, f ...

Ways to clear TextField status

My question is about a Textfield. In the case where the state is null but the text field value is showing in the Textfield. <TextField style={{ width: '65%'}} id="standard-search" ...

Organizing AngularJS Data by Initial Letter with the <select></select> HTML Element

I'm trying to figure out how to filter an ng-repeat function based on the first letter of each option. For example, I want to filter a set of array or string so that only options starting with "A" or "B" are displayed. Can anyone help me with this? H ...

Unique Google Maps API V3 PEGMAN Customization

Can custom zoom controls and Pegman controls be styled with the same design? To add custom zoom controls, follow the instructions provided in this question's answer: <!DOCTYPE html> <html> <head> <meta name="viewport" cont ...

The render of Javascript is not functioning properly in Chromedriver

For website testing in VisualStudio, I planned to use Selenium with Cromedrive. Unfortunately, I encountered difficulty in seeing items generated by Javascript on the page. It appears that chromedriver captures the pagesource before the JS has a chance to ...

Creating an HTML file using PUG in a local environment (using npm and gulp)

Is there a way to automatically generate an HTML file with the same name as my Pug file whenever I save using gulp? I've checked all the documentation on but it only explains how to return Pug content in console... ...

When utilizing `Router.push()`, the `fs.readdirSync` function does not function as expected

One of my pages contains a button that redirects the user to the root page ('/'). However, the server-side code on the root page is not triggered when I use Router.push(), leading to an error due to node fs being used in the code. Is there a way ...