Implement a for loop within the function responsible for creating a collection in Firebase

I am currently developing a food application using Ionic (4) /Angular that can manage multiple stores and integrates Firebase. However, I have encountered a problem. When creating a new order, I use the following code:

add(stores: Array<CartStore>, address: string) {
 this.afs.collection<Order>('orders').add({
          userId: this.userId,
          address: address,
          items: stores.items,
          store: {
            id: stores.id,
           name: stores.name,
          }
        });     
      }

To create a SINGLE order, I need to use a for loop within the function as shown below:

 for(let i in stores){
items: stores[i].items,
          store: {
            id: stores[i].id,
           name: stores[i].name,
          }
}

However, this is not feasible within the Firebase collection function... Frustrating!

Here is an overview of how my app operates:

Users click on the checkout button, initiating the following function:

this.orderProvider.add(this.cart.stores, this.address);

Here are the models utilized in my app:

Cart.ts

import { CartStore } from "./cart-store";

export class Cart {
  id?: string;
  userId: string;
  total: number;
  stores: Array<CartStore>;
}

Order.ts

import { CartStore } from "./cart-store";

export class Order {
  id?: string;
  userId: string;
  total?: number;
  address: string;
  status?: string;
  orderNumber?: string;
  createdAt?: number;
  updatedAt?: number;
  store: CartStore;
  items: Array<CartStore>;
  isReviewed?: boolean;
}

Cart-Store.ts

import { CartItem } from './cart-item';

export class CartStore {
  id?: string;
  name: string;
  subTotal?: number;
  items?: Array<CartItem>;

  constructor() {
  }
}

Cart-Item.ts


import { Variation } from "./variation";
import { ItemReview } from "./item-review";
import { Size } from "./size";

export class CartItem {
  id?: string;
  name: string;
  price: number;
  quantity: number;
  thumbnail: string;
  variations: Array<Variation>;
  size: Size;
  subTotal: number;
  review?: ItemReview;

  constructor() {
  }
}

I appreciate any assistance provided! I am relatively new to this field.

Answer №1

I attempted to implement the following code snippet:

add(stores: Array<CartStore>, address: string) {
    for (let i in stores) {
      if (stores[i] && stores[i].items && stores[i].items.length) {
        this.afs.collection<Order>('orders').add({
          userId: this.userId,
          address: address,
          items: stores[i].items,
          store: {
            id: stores[i].id,
            name: stores[i].name
          }
        });
      }
    }
  }

However, instead of creating a single order with all items, this code snippet generates multiple orders (one for each item).

Answer №2

This is my store.service.ts

import { Injectable } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { Store } from '../models/store';
import {map} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class StoreService {

  constructor(public afs: AngularFirestore) {

  }

  all() {
    return this.afs.collection<Store>('stores/').snapshotChanges().pipe(map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Store;
        const id = a.payload.doc.id;
        return {id, ...data};
      });
    }));
  }

  get(id: string) {
    return this.afs.doc('stores/' + id).valueChanges();
  }
}


Additionally, here is my store.ts

export class Store {
  id?: string;
  name: string;
  address: string;
  itemCount?: number;
  rateCount?: number;
  rating?: number;

  constructor() {
  }
}

My firebase account is linked to two separate apps - one for customers and the other for admins (store account). Interestingly, I have noticed that there is only one admin account stored in firebase.

Answer №3

A handy way to achieve this is by utilizing a for...of loop:

createOrder(stores: Array<CartStore>, address: string) {
    for (const store of stores) {
      if (store && store.items && store.items.length) {
        this.afs.collection<Order>('orders').add({
          userId: this.userId,
          address: address,
          items: store.items,
          store: {
            id: store.id,
            name: store.name
          }
        });
      }
    }
  }

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

Error: Firebase Error - Unable to find Firebase App 'default'. Please ensure that Firebase App.initializeApp() is called before trying to access the app

Hello, I'm really struggling with this issue - despite reading through multiple posts here, I can't seem to fix this error. Here is the code snippet from my init.js: import firebase from "firebase/app" var config = { apiKey: "A ...

Can you explain the significance of 1x, 3x, etc in the Karma code coverage report for Angular unit testing?

I am a beginner when it comes to Unit Testing in Angular. Recently, I set up karma with code coverage using angular-cli. After running the command ng-test, I checked out the code coverage report and noticed references like 1x, 3x, etc. next to my code line ...

Encountering issues with `npm run build:prod` on Ubuntu 16.04, whereas it runs smoothly on

I've encountered errors when attempting to run "npm run build:prod" on Ubuntu 16.04, even though I don't face the same issues on Windows 10. Both npm and node are up-to-date. It's unclear whether the problem lies with npm or angular. After ...

The create document feature seems to be malfunctioning for some reason. Any ideas why it's not working properly in Firebase with Angular

I've been attempting to submit user data to the Firebase Firestore database, but I'm experiencing issues with the function that is supposed to create a new collection. Despite trying different methods, none of them seem to be working for me. I ha ...

When working with create-react-app and TypeScript, you may encounter an error stating: "JSX expressions in 'file_name.tsx' must

After setting up a React project with TypeScript using the CLI command create-react-app client --typescript, I encountered a compilation error when running npm start: ./src/App.js Line 26:13: 'React' must be in scope when using JSX react/r ...

The parseString method is unable to find the specified member

I have an XML file that needs to be converted to JSON for use in my application. The service returns the XML file like this: constructor(private http: HttpClient) { } loadXml() { return this.http.get('../../assets/1bbc5495-3872-4058-886e-aeee2a1cd ...

Tips for utilizing the JS attribute "offsetWidth" within Angular 4

I am attempting to retrieve the width of an element using JavaScript in my Angular application. document.getElementsByClassName("element")[0].offsetWidth; However, I keep encountering the following compilation error: Property 'offsetWidth' d ...

Configure NODE_OPTIONS to set the maximum old space size for an Angular application to Nx

In my Angular application within an Nx workspace, I am utilizing the @nx/angular:webpack-browser executor for building. "build": { "executor": "@nx/angular:webpack-browser", ... } This is a sizable application that necessita ...

Error encountered in React component: TypeScript TS2339 states that the property 'xyz' is not found on type 'IntrinsicAttributes...'

I am attempting to develop a straightforward React component that can accept any properties. The syntax below using any is causing issues (unexpected token just before <): export class ValidatedInput extends React.Component<any, any> {...} The p ...

Replacing a component dynamically within another component in Angular 2

I am currently working on integrating a component within another component that has its own view. The component being loaded will be determined dynamically based on specific conditions. Essentially, I am looking to replace one component with another compo ...

Angular loses focus on MatTableDataSource after updates

Have you encountered the issue where the focus disappears after updating an input element in one row and clicking on the input in the next row? This happens because the datasource gets updated. I have been trying to find a way to preserve the focus while ...

Passing Toastr to child component in Angular 4 was successfully implemented

I am working with a parent component that utilizes ng2-toastr version 4.1.2. Parent Component: import { Component, ViewContainerRef } from '@angular/core'; import { AfterViewInit, ViewChild } from '@angular/core'; import { Rou ...

Unable to render a stationary image located within the component's folder in Angular

Within the components directory, I have placed an image file. It's a simple PNG with a logo on it. The four files in the directory are: blobb.png blobb.comp.ts blobb.comp.html blobb.comp.scss In the HTML file, I included the image using a static so ...

What is the best way to pass a value to a modal and access it within the modal's component in Angular 8?

How can I trigger the quickViewModal to open and send an ID to be read in the modal component? Seeking assistance from anyone who can help. Below is the HTML code where the modal is being called: <div class="icon swipe-to-top" data-toggle="modal" da ...

Identifying the modifications made to a Firestore list, including additions, deletions, and changes

Utilizing Firestore as the backend has allowed me to navigate basic crud methods effectively. However, I am curious about how to identify changes within a list of returned items after the initial subscription. My goal is twofold: - Minimize the number of ...

The 'asObservable' property is not present on the type '() => any'.ts(2339)

Error: Property 'asObservable' does not exist on type '() => any'.ts(2339) Error: Property 'subscribe' does not exist on type 'Subscription'. Did you mean 'unsubscribe'?ts(2551) Error: Property 'sub ...

Is it feasible to add to an ID using ngx-bootstrap's dropdown feature?

In the documentation for ngx dropdown, there is a feature called "append to body." I recently tried changing this to append to a table element instead and it worked successfully. Now, on another page, I have two tables displayed. If I were to assign each ...

Class property in Typescript is initialized in the constructor, but is undefined in a member function

I'm encountering a recurring problem while developing an Electron application using Typescript. The backend has a set of controllers, with the AppController managing file system interactions and WindowController handling basic window functions. Here&a ...

JavaScript: exporting everything from ... causing excessive bloat in the build file

After building my react-app with create-react-app, I noticed a decline in performance. Here is the structure of my project: /store actions.ts reducers.ts /module1 module1.actions.ts module1.reducers.ts /moduleN moduleN.actions.ts m ...

Avoid accessing invariant variables when mocking: __extends

I'm currently in the process of converting a collection of react components from JavaScript to TypeScript, and I've encountered an issue with jest.mock(). Before: "react": "^15.6.1" "jest": "20.0.4" "enzyme": "^2.9.1" CustomDate.js ... import ...