The JSON object array is not empty, but it is unable to be iterated using a foreach loop, displaying a

Exploring a library of books from a Firestore collection in the create() method.

The book data is stored in an array called checkout which is initialized in the data() method.

export default {
  name: "checkout-history",
  data() {
    return {
      checkout: []
      ]
    };
  },
  created() {
    db.collection("checkout")
        .get()
        .then(querySnapshot => {
          querySnapshot.forEach(doc => {
            const data = {
              id: doc.id, // firebase document id
              book_did: doc.data().book_did,
              borrowed_date: doc.data().borrowed_date,
              copies_did: doc.data().copies_did,
              due_date: doc.data().due_date
            };
            this.checkout.push(data); // add to array
          });
        });

      console.log(this.checkout)  // displaying data, as seen in the image below

      console.log(this.checkout.length)  // returns 0
      console.log(Object.keys(this.checkout).length)  // returns 0
      }
      ......

Upon running console.log(this.checkout);, the console displays the data and structure.

https://i.sstatic.net/YqVyl.png

Despite this, I am unable to iterate through the array, as this.checkout.length remains 0

I attempted to use Object.keys but faced similar results.

Object.keys(this.checkout).forEach(key => {
     const keys = this.checkout[key];
     console.log(keys);
});

Feeling puzzled and out of solutions.

I have researched various solutions online, but none seem to work.

Answer №1

Perhaps you're running your script before the request has finished processing.

When you place your mouse cursor over the small blue i icon, a tooltip appears:

The value below has just been evaluated.

Answer №2

When working with Firestore (or most modern web APIs), data is loaded asynchronously. This means that your code will continue to run after initiating a query, and once the data is retrieved from the database, the then() callback will be triggered. As a result, any code that requires access to this database data must be placed within the then() callback.

db.collection("checkout")
    .get()
    .then(querySnapshot => {
      querySnapshot.forEach(doc => {
        const data = {
          id: doc.id, 
          book_did: doc.data().book_did,
          borrowed_date: doc.data().borrowed_date,
          copies_did: doc.data().copies_did,
          due_date: doc.data().due_date
        };
        this.checkout.push(data); 

        console.log(this.checkout)  

        console.log(this.checkout.length)  
        console.log(Object.keys(this.checkout).length)  
      });
    });

  }
  ......

For further reference, you can also check out:

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

The change event for the select element is malfunctioning

Currently, I am deep diving into Nodejs with the second edition of the node cookbook. This book has caught my attention because it explains concepts using practical sample code, making it easier to grasp. The example code I am working on is related to Br ...

Enhance Three.js 3D model visuals with textured surfaces using Fabric.js canvas as a dynamic texture

Exploring the world of Three.js for the first time, I am embarking on a project that involves leveraging a pre-existing 3D model and altering one of its materials to utilize a Fabric.js canvas as its texture. However, I've hit a roadblock where the te ...

Start the input field with the prefix "APP" and restrict the input to only numbers

My challenge involves creating an input field that requires a prefix of "APP " followed by 7 numeric digits. I initially considered using ngx-mask, but it appears to be impossible. Another approach I thought of was utilizing the (focusin) event like this: ...

How can a key press be simulated without specifically targeting an element?

Is it possible to simulate a key press without targeting any specific element? I found this code snippet: var press = jQuery.Event("keypress"); press.ctrlKey = false; press.which = 75; $("whatever").trigger(press); The above code is used to simulate pres ...

Ways to distinguish between two div elements that have scroll bars and those that do not

I created a div with CSS styling. .comment-list { margin: 20px 0; max-height: 100px; min-height: 100px; overflow-y: scroll; width: 100%; background-color:#000; } Here is the HTML code for the div: <div class="comment-list"> </div> When the ...

Trouble deploying Firebase Cloud Functions

I am attempting to implement the following two functions: exports.increaseWaitinglistCounters = functions.database .ref('waitinglists/$iid/$uid') .onCreate(async () => { await admin .database() .ref(`waitinglistCounters/$ii ...

Loop through the XML string inside a for loop using Javascript

Hey everyone, I'm having some trouble with looping through strings for XML inside a for loop. I've attempted the following code but the loop doesn't seem to be working: var data = [{"name": "Tom", age: "20"}, {& ...

Using JQuery to locate and substitute occurrences of HTML elements throughout my webpage

Looking for assistance with a JQuery search and replace task involving multiple instances of HTML within a specific DIV element on my webpage. Specifically, I need to change certain items in the textbox to a simpler display format. Here is a snippet of th ...

I need guidance on how to successfully upload an image to Firebase storage with the Firebase Admin SDK

While working with Next.js, I encountered an issue when trying to upload an image to Firebase storage. Despite my efforts, I encountered just one error along the way. Initialization of Firebase Admin SDK // firebase.js import * as admin from "firebas ...

Add HTML to a div element using jQuery when content is replicated through JavaScript

I have encountered an issue while appending HTML from a dynamically created div using JavaScript. The problem arises when I try to append the HTML multiple times - each time it adds the content twice, thrice, and so on. This is possibly happening because i ...

Selenium-webdriver is having trouble locating an element through the CSS selector

I encountered an issue while using selenium-webdriver in JavaScript to input a value into a field. Here is my test.js code: async () => { let driver = await new webdriver.Builder().forBrowser("chrome").build(); try { await driver.get("http://te ...

Obtain a specific value from JSON data that is nested within other data

Here is the code snippet I'm using to extract a log entry: 2020-01-11 17:47:16 [root] INFO: A contact with email [email protected] already exists. I'm questioning if using .get("errors", {})[0].get('message') is the correct a ...

Ways to retrieve the responseText within the jqxhr.complete callback function

Apologies in advance for my lack of knowledge in JavaScript and jQuery, this question may seem basic. I've searched through the jQuery documentation and Google but couldn't find an answer. I am attempting to trigger an action on the response onc ...

Implement the addition of subcollections to a unified identification document in Firestore

I am struggling to store the URLs of multiple images (previously saved in Storage) in a subcollection of a Firestore document. Although I have managed to do it, each image generates a new document with its corresponding sub collection img, which is not my ...

Using jQuery to extract the HTML content of an element while removing the style attribute

Is there a way to retrieve the raw HTML of an element, or obtain the HTML without the "style" attribute applied? Let's consider the example below: <div class="outer"> <div class="inner"> some text </div> </div> A ...

Using Javascript to attach <head> elements can be accomplished with the .innerHTML property, however, it does not work with XML child nodes

Exploring new ways to achieve my goal here! I want to include one JS and one jQuery attachment for each head section on every page of my static website. My files are: home.html <head> <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

Create a PDF using puppeteer without the need to save it

I am currently working on an API built with node.js hosted on heroku, while my frontend application is created using Vue.js and deployed on hostinger. I am interested in exploring the possibility of generating a PDF file using puppeteer and sending it dire ...

Challenges in establishing the initial connection between Express.js and MongoDB

Having spent a significant amount of time researching how to set up MongoDb in an Express/NodeJs application, I believed I had a good understanding of how to implement it efficiently. I decided to initialize my mongodbConnection in the WWW file provided by ...

Why am I consistently obtaining NaN as the output for the majority of my calculations?

Looking to calculate the average of cities in each state using the Reduce Function in mongoDB, but encountering an issue where only one correct result is obtained while rest return as 'nan'. Below is the map function: function map(){ key = {sta ...

The system encountered an issue while trying to access the 'bannable' property, as it was undefined

message.mentions.members.forEach(men => { let member = message.mentions.members.get(men) if (!member.bannable) return message.reply(not_bannable) const reason = args.slice(1).join(" "); member.ban({reason: reason ...