The Angular Firebase query is being run repeatedly

I'm currently facing an issue in my project where Firebase queries are being executed multiple times. This problem wasn't present during development and no changes have been made to the Firebase dependencies.

Below is a snippet of code that used to run once but now runs multiple times:

  ngOnInit(): void {

this.array = [];

// Try-Catch function reading data from Firestore
try {

  this.db.collection("myCollection").where("Age", "==", "20").onSnapshot(snapshot => {
    snapshot.docs.forEach (() => {

      this.db.collection('Jobs').get().then (snapshot2 => {
        snapshot2.docs.forEach (snapshot3 => {

          if (snapshot3.id.includes('Unemployed')){

              this.array.push(
                {
                  ID: snapshot3.id
                }
              );
          }
        })
      })
    })
  })
  
} catch (error) {
  console.log(error.message);
}

}

Any assistance on resolving this issue would be greatly appreciated. Thank you!

Answer №1

To manage this scenario, you can proceed as follows:

dataList: any[] = [];
  ngOnInit() {
    // Initializing the array to store data

    if (!this.dataList || !this.dataList.length) {
      // Try-Catch block to fetch data from Firestore
      try {
        this.db
          .collection("myCollection")
          .where("Age", "==", "20")
          .onSnapshot(snapshot => {
            snapshot.docs.forEach(() => {
              this.db
                .collection("Jobs")
                .get()
                .then(snapshot2 => {
                  snapshot2.docs.forEach(snapshot3 => {
                    if (snapshot3.id.includes("Unemployed")) {
                      this.dataList.push({
                        ID: snapshot3.id
                      });
                    }
                  });
                });
            });
          });
      } catch (error) {
        console.log(error.message);
      }
    }
  }

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

Rails 3.2 - form mistakenly submitted repeatedly

I am working on a project involving the Box model, which includes many box_videos. I have created an edit form to allow users to add box_videos to the box after it has been created: <%= form_tag "/box_videos", { method: :post, id: "new_box_videos", rem ...

I need help figuring out how to create dynamic bars that change colors based on their values. Any suggestions on how to

Seeking a solution to create interactive live-charts similar to the image provided. I've explored various chart libraries like Highcharts, fusioncharts, raphaeljs and many others, but haven't found one that fits my needs perfectly. I experimented ...

Integrating a third-party plugin into an Angular 4 component

I am interested in integrating a 3rd party plugin into a component, such as CKEDITOR or even a jQuery plugin. While I am aware of the ng-ckeditor package, I prefer not to use it because I want the flexibility to incorporate any plugin in the future withou ...

Implementing pagination in an express application

I am faced with a situation where I have an array of JSON objects generated by a function in my running Express app. When there is only one object, it is rendered using the following Jade view. p You searched for '#{prop}' h2 Result if res ...

Is there a way to sort search outcomes by a drop-down menu in Next.js?

I am currently working on implementing a filter for my data based on selections made in a drop-down menu. Here's the setup: I have MSSQL data being pulled into NextJS using Prisma (ORM). My goal is to create a dropdown filter that will refine the di ...

What strategies can be used to effectively manage multiple asynchronous requests?

I have two requirements: one is to load an image (which will take a long time on the backend server), and the other is to perform an AJAX request. I would like it to be structured like this: $.when( [perform image loading] [perform ajax request] ).t ...

Is there a way to direct the embedded YouTube video on my HTML website to open in the YouTube application instead?

My website has embedded Youtube videos, but when viewing on a mobile browser they open in the default player. I want them to open in the Youtube application instead, as my videos are 360 degrees and do not work properly in the default browser player. ...

Exploring the iteration of objects utilizing underscore.js

Currently, I am diving into the world of backbone.js and encountering a slight issue while iterating over some models in a view. The first code snippet seems to be functioning correctly, but the second one, which is underscore.js-based, does not work as ex ...

Avoiding the pitfalls of hierarchical dependency injection in Angular 6

Too long; didn't read: How can I ensure that Angular uses the standard implementation of HttpClient in lower level modules instead of injecting a custom one with interceptors? I have developed an Angular 6 library using Angular CLI. This library expo ...

Mastering ReactJs: The Ultimate Guide to Updating State Properties

I've been attempting to change the isSelected property for a specific row in my state data, but am finding that it's not updating. Can someone please offer guidance on the most effective approach to achieve this? var selecte ...

JavaScript tool: Verify the presence of both jQuery and jQuery UI

I have been working on developing a Javascript Widget (almost complete), and when integrating it into the first site I encountered some issues. My Widget requires loading multiple libraries (jquery, jquery ui, mustache, ...); this is achieved by injecting ...

Leverage access tokens in React.js frontend application

After successfully creating an authentication API using Nodejs, Expressjs, MongoDB, and JWT, I am now working on a small frontend application with React-js specifically for Sign-up and Sign-in functionalities. While I have managed to integrate the Sign-up ...

Error in Chrome Extension Data Type

I am having trouble adding a highlighted red button to YouTube. The code does not seem to be working as expected. manifest.json { "name": "Example", "version": "0.0", "manifest_version": 2, "c ...

What is the best approach to testing the React Hook "useEffect" that is used to make an API call with Typescript?

Currently, I am working on writing Jest-enzyme tests for a basic React application using Typescript along with the new React hooks. The main issue I am facing is with properly simulating the api call made within the useEffect hook. Within the useEffect, ...

I am experiencing a lack of results when attempting to run db.find() in Mongodb

Recently I delved into the realm of MongoDB, deciding to create a basic application that simply showcases data stored in my database. Check out the code snippet below: var mongoose = require("mongoose"); mongoose.connect("mongodb://localhost ...

Choosing various choices using AngularJS

My goal seems simple using vanilla JS, but with AngularJS, I'm looking for the best way to achieve it within the framework. I aim to update the selected options in a multiple select box without adding or removing any options. Below is a snippet of my ...

Loop through the list items using jQuery and retrieve the value of the data-imgid attribute

Multiple li elements have a unique data-id attribute, as shown below: <ul> <li data-imgid="5" class="getMe">some text</li> <li data-imgid="6" class="getMe">some text</li> <li data-imgid="7" class="getMe">some t ...

Initiating external libraries at the right time in Angular 4

I am currently experimenting with a UI kit (you can check it out here) that comes with multiple JavaScript files, jQuery, Bootstrap, and its own components. I have included them in my index.html file and everything works perfectly as long as the checkbox ...

Troubleshooting undefined value issue with pagination in AJAX GET request with Laravel

I am currently working on a GET request using AJAX. In my Laravel Controller, I attempted to use "->paginate(5);" and encountered undefined values. However, when I use "->get();", it works flawlessly. Nevertheless, I prefer to use paginate to impleme ...

Tips on transferring a substantial array value from JavaScript to PHP

I am looking to create multiple xml requests and store the resulting data in an array for pagination purposes. For example, if I receive 4000 records, I want to display 40 records per page and be able to navigate through pages without making additional xml ...