Tips for Decreasing Query Time with MatTable and MatTableDataSource

When working with my firestore database, I am trying to query documents and display them while also calculating the total value of a specific column (promiAmount).

I have successfully displayed the values in a mat table, but I'm struggling to calculate the sum of a particular column (promiAmount).

Despite trying various methods, I keep ending up with an undefined result. It seems like I'm missing a step somewhere, but I can't seem to figure it out.

Here is the model I am working with:

export class PromisoryModel {
    customerAccountNo: string;
    customerName: string;
    customerNo: string;
    transactionDate: string;
    promiFlag:number;
    promiAmount: number;
}

Actual Data from Firestore

{
  "2vnLBK4qGBd4ZNbPz9aq": {

    "customerAccountNo": "100-PDQ-12-17",
    "customerName": "TEST, CUSTOMER 1",
    "customerNo": 17,
    "promiAmount": 1667,
    "promiFlag": 3,
    "transactionDate": "2022-02-15"
  },
  "CcK8Ju8ANOM561UyGPPf": {
    "customerAccountNo": "100-PDQ-12-17",
    "customerName": "TEST, CUSTOMER 1",
    "promiAmount": 1667,
    "promiFlag": "3",
    "transactionDate": "2022-02-15"
  },

Component TypeScript Code:

import { Component, OnInit, ViewChild } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/compat/firestore';
import { Observable} from 'rxjs';
import { PromisoryModel } from 'src/app/models/promisory.model';

@Component({
  selector: 'app-members',
  templateUrl: './members.component.html',
  styleUrls: ['./members.component.scss']
})

export class MembersComponent implements OnInit {
  private PromisorryCollection : AngularFirestoreCollection<PromisoryModel>;
  promissory: Observable<PromisoryModel[]>;

  constructor(public afs: AngularFirestore) {}

  // declarations
  queryName: any;
  promiList: PromisoryModel[];
  getCsrBadge: any;

  
  queryDetails() {
    this.PromisorryCollection = this.afs.collection('promisory',
    ref => ref
    .where('customerName','==', this.queryName)
    .orderBy('transactionDate','desc')
    )
   this.promissory = this.PromisorryCollection.valueChanges();
   this.promissory.subscribe(
      (data) => (this.dataPromiSource = new MatTableDataSource(data),  
      )
   )
  }
}
  

Attempt 1: Result is undefined

this.PromisorryCollection = this.afs.collection('promisory',
    ref => ref
    .where('customerName','==', this.queryName)
    .orderBy('transactionDate','desc')
    )
   this.promissory = this.PromisorryCollection.valueChanges();
   this.promissory.subscribe(
      (data) => (this.dataPromiSource = new MatTableDataSource(data),
      
      this.getCsrBadge = (data).reduce((acc, cur)=> {
        return acc + cur.promiAmount
      },0)
      )
   )

   console.log(this.getCsrBadge)

Attempt 2: Result is undefined

this.PromisorryCollection = this.afs.collection('promisory',
    ref => ref
    .where('customerName','==', this.queryName)
    .orderBy('transactionDate','desc')
    )
   this.promissory = this.PromisorryCollection.valueChanges();
   this.promissory.subscribe(
      (data) => (this.dataPromiSource = new MatTableDataSource(data),
      this.promiList = (data),
      this.getCsrBadge = this.promiList.reduce((acc, cur)=> {
        return acc + cur.promiAmount
      },0)
      )
   )

Attempt 3: result is undefined

 this.PromisorryCollection = this.afs.collection('promisory',
    ref => ref
    .where('customerName','==', this.queryName)
    .orderBy('transactionDate','desc')
    )
   this.promissory = this.PromisorryCollection.valueChanges();
   this.promissory.subscribe(
      (data) => (this.dataPromiSource = new MatTableDataSource(data),
      this.dataPromiSource.filter = this.queryName.trim().toLowerCase(),
      this.getCsrBadge = this.dataPromiSource.filteredData.map( amount => amount.promiAmount).reduce((acc,cur) => acc + cur,0)
      )
   )
   
   console.log(this.getCsrBadge)

Attempt 4: result is undefined

this.PromisorryCollection = this.afs.collection('promisory',
    ref => ref
    .where('customerName','==', this.queryName)
    .orderBy('transactionDate','desc')
    )
   this.promissory = this.PromisorryCollection.valueChanges();
   this.promissory.subscribe(
      (data) => (this.dataPromiSource = new MatTableDataSource(data),
      data.filter = this.queryName.trim().toLowerCase(),
      this.getCsrBadge = this.dataPromiSource.filteredData.map( amount => amount.promiAmount).reduce((acc,cur) => acc + cur,0)
      )
   )
   
   console.log(this.getCsrBadge)

Answer №1

Through various experiments and with the guidance of @priyashree's reference, it was discovered that we were inadvertently passing empty data to our array. (Apologies for overlooking this mistake due to inexperience)

In our original Second Attempt, we were simply passing our subscription data/observable to our mat-table datasource.

The Second Attempt works perfectly if we adjust the order as follows:

this.PromisorryCollection = this.afs.collection('promisory',
    ref => ref
    .where('customerName','==', this.queryName)
    .orderBy('transactionDate','desc')
    )
   this.promissory = this.PromisorryCollection.valueChanges();
   this.promissory.subscribe(
      (data) => (
      this.promiList = (data),
      this.getCsrBadge =this.promiList.reduce((acc, cur)=> {
        return acc+ cur.promiAmount
      },0),
      this.dataPromiSource = new MatTableDataSource(data))
   )

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

Updating nested interface values using React hooks

I am looking to develop an application that can seamlessly update a nested configuration file after it has been imported (similar to swagger). To achieve this, I first created a JSON configuration file and then generated corresponding interfaces using the ...

Using Vivus.js in an Angular 5 Component

I am currently facing some challenges while attempting to incorporate Vivus.js library into Angular 5. The issue seems to be arising from the constructor of Vivus, which suggests that the library is being loaded correctly but not recognizing my element id. ...

Confirm your identity without using a Single Sign-On (SSO) system

My current situation involves a PHP-based website where users login using credentials stored in a database. Additionally, we have another SPA website with .NET CORE as the API layer. Unfortunately, we do not have the option of utilizing a central authent ...

Utilizing TypeScript interfaces to infer React child props

How can I infer the props of the first child element and enforce them in TypeScript? I've been struggling with generics and haven't been able to get the type inference to work. I want to securely pass component props from a wrapper to the first ...

The MemoizedSelector cannot be assigned to a parameter of type 'string'

Currently, my setup involves Angular 6 and NgRX 6. The reducer implementation I have resembles the following - export interface IFlexBenefitTemplateState { original: IFlexBenefitTemplate; changes: IFlexBenefitTemplate; count: number; loading: boo ...

Issue with API/CORS not fetching while utilizing react-email in ASP.NET/React.JS application

My React App is running at port 44411 and react-email is running at port 3000. I followed a tutorial on setting up react-email, but it didn't work initially. After some troubleshooting, I managed to make my API request go through Postman. The next st ...

Utilize an external JavaScript function within a React and TypeScript document

I have encountered an issue in my React/Next.js/TypeScript file where I am trying to load the YouTube iframe API in my useEffect hook. Here is the code snippet: useEffect(() => { const tag = document.createElement('script'); tag.src = ...

Enhancing Typescript Arrow Function Parameters using Decorators

Can decorators be used on parameters within an arrow function at this time? For instance: const func: Function = (@Decorator param: any) => { ... } or class SomeClass { public classProp: Function = (@Decorator param: any) => { ... } } Neither W ...

At first, the Angular disabled property does not seem to be functioning as

Trying to toggle a button's disabled state based on whether an array is empty or not in an Angular application. The button implementation looks like this: <button (click)="doStuff()" [disabled]="myObject.myArray.length === 0"> ...

Angular Proxy is not passing the WebSocket Upgrade Header

When using the Angular CLI proxy by running ng serve --proxy-config proxy.conf.json the configuration looks like this: { "/api/*": { "ws": true, "secure": false, "target": "http://localhost:80", "logLevel": "debug" ...

In Laravel, a post request can pass a class with a property that is of a different class type

In my Laravel controller, I have the following function: public function save(Request $request, ClientOrderDTO $clientOrderDTO){ } The definition of the ClientOrderDTO used above is as follows: use App\DTO\ClientDTO; class ClientOrderD ...

Implementing Material Design in React using TypeScript

I'm currently in search of a method to implement react material design with typescript, but I've encountered some challenges. It appears that using export defaults may not be the best practice due to constraints in my tsconfig. Is there an al ...

The error message "vimeo/player.js - Unable to access property 'nativeElement' as it is undefined" appeared

I am encountering difficulties integrating vimeo/player.js into my angular-cli application. There isn't a supporting library for Angular 4, so I'm following the steps in the README.md under "Using with a module bundler". I created a vimeo-player ...

In Node.js, when accessing a Firebase snapshot, it may return a

Currently, I am utilizing Firebase functions to execute the code for my Flutter application. This code is responsible for sending push notifications to my app. However, I am encountering an issue where I receive a null value at snap.val(). Take a look at h ...

The continuous loop is triggered when attempting to pass array data from the API

Hello, I have been searching for a solution to my current issue without much success. The problem revolves around retrieving dates from Firebase and populating them into UI elements in my Vue app. My end goal is to align each date with the corresponding mo ...

Having trouble with Socket.io sending data to a specific socketId?

I'm currently using Socket.Io 1.7.3 with Angular 2, connecting to a ExpressJS Server. I'm facing an issue where I am unable to send packages to a specific socket ID even though they are a match. Server code snippet: socket.on('subscribeNot ...

Steps to include a horizontal divider in the footer section of an angular-material table

Is it possible to add a line between the last row (Swimsuit) and the footer line (Total)? If so, how can I achieve this using Angular 15? https://i.stack.imgur.com/581Nf.png ...

Struggling to translate JavaScript code into Typescript

Currently in the process of converting my JavaScript code to Typescript, and encountering an error while working on the routes page stating Binding element 'allowedRoles' implicitly has an 'any' type. ProtectedRoutes.tsx const Protecte ...

How to Ensure the Final Column in an Angular Bootstrap Row Occupies the Remaining Available Space

Within my Angular5 application, there is a container component used to display a row with multiple components arranged in n columns, as shown below: <div class="row mx-5 my-5 h-75 w-80"> <div class="col-md-4 col-lg-4 m-0 p-0" *ngIf="advanc ...

Alternating the main access point from a separate module

I'm finding it difficult to understand why this should be so simple, but I just can't seem to solve this issue. Within my application, I have various root routes like login, events, and more. To manage the main menu functionality, I created a mo ...