Extracting information from AngularFirestore in HTML and passing it to TypeScript

In my latest project using Angular-Firestore, I am facing an issue with getting data from the HTML page and inserting it into a list of data using *ngFor. Every time I press the submit button on the form, some user input data is required while other data comes from the *ngFor loop. Unfortunately, I keep encountering the following error message: SellinglistComponent.html:53 ERROR Error: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field ownerID)

Interestingly, when I click the submit button twice, the process works smoothly without any errors, and I can see the data being sent to the database. Can anyone help me understand why this may be happening? Any guidance on how to solve this issue would be greatly appreciated. Thank you.

Here is the TypeScript file:

Answer №1

The reason behind the error message

SellinglistComponent.html:53 ERROR Error: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field ownerID)
is due to the asynchronous nature of the function being called.

When you execute

this.db.collection("bids").add({})
, the response from
this.db.collection('saleCrops').doc(this.bidObjectId).ref.get()
has not been received yet. This is why this.ownerId is not set when it is accessed for the second time.

To confirm this, you can log this.ownerId just before calling

this.db.collection("bids").add({})
.

A possible solution is to make the function asynchronous.

async addBid(bidObj)

Then use await when calling the following line.

await this.db.collection('saleCrops').doc(this.bidObjectId).ref.get()

Since the two blocks of code are interdependent, you can refactor as follows:

Instead of assigning

this.ownerID = doc.data().posterID;

You can return the value like this.

    await this.db.collection('saleCrops').doc(this.bidObjectId).ref.get()
        .then((doc) => {
            if (doc.exists) {
                return doc.data().posterID;
            }
        }).then(id => {
            this.db.collection("bids").add({})
        }).catch(error => console.error(error));

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

Hold off on proceeding until the subscription loop has finished

Is there a way to verify that all results have been successfully pushed to nodesToExpand after running the for loop? The getFilterResult function is being called via an HTTP request in the nodeService service. for(var step in paths) { this.nodeSe ...

What sets apart the commands npm install --force and npm install --legacy-peer-deps from each other?

I'm encountering an issue while trying to set up node_modules for a project using npm install. Unfortunately, the process is failing. Error Log: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolv ...

Challenges with TypeScript's typeof operator and instantiation of classess

Discussing the scenario of a map setup: const map = { a: ClassA, b: ClassB, c: ClassC, } The purpose of this map is to link different classes together. There exists a function that returns an instance of a class based on a key in the map ...

AngularTS regex that enforces the use of a decimal point in numbers

I am working on a requirement where the input should only accept decimal characters, negative or positive. I need to use regex to make the decimal point mandatory, however it is currently allowing negative whole numbers which is not the desired behavior. I ...

Leverage the child interface as a property interface containing a generic interface

I'm facing an issue while trying to incorporate typings in React. The concept is centered around having an enum (EBreakpoint) that correlates with each device we support. A proxy wrapper component accepts each device as a prop, and then processes the ...

Is there a way to reset the yAxes count of a chart.js chart in Angular when changing tabs?

I am currently using chart.js within an Angular framework to visually display data. Is there any method available to reset the y-axis data when changing tabs? Take a look at this Stackblitz demo for reference. Upon initial loading of the page, the data ...

Leverage the generic parameter type inferred from one function to dynamically type other functions

I am in the process of developing an API for displaying a schema graph. Here is a simplified version of what it entails: interface Node { name: string; } type NodeNames<T extends Node[]> = T[number]["name"]; // Union of all node names as strings ...

Employing strict mode, albeit with certain exceptions

When using the compiler strict mode ("strict": true), errors occur for my models that are structured like this: @Entity class MyModel { @Column() public name: string; @Column() public email: string; ... } The specific errors enc ...

Launching superheroes application developed with Angular 2

I followed the heroes tutorial and customized my own Angular2 application using some components. Although it resembles the heroes tutorial, I have successfully set up everything with my IDE and npm. Now, I am facing challenges in deploying my application i ...

When the session times out in Angular 5, the previous user's credentials remain on the page instead of being replaced with the current user's information

When switching from one user to another in Angular 5, I am facing an issue where the previous user's credentials are displayed instead of the current user's until I refresh the page. I have tried using the localstorage.clear() method but it doesn ...

Obtaining a return value from a function in Angular

After just starting to work with Angular, I am attempting to extract a value from a button displayed in the HTML using a function. `<button class="btn" id="btn-gold" (click)="value(9)" name="mybutton" value="9">` 9 I have also inclu ...

Guide on how to address the problem of the @tawk.to/tawk-messenger-react module's absence of TypeScript definitions

Is there a way to fix the issue of missing TypeScript definitions for the @tawk.to/tawk-messenger-react module? The module '@tawk.to/tawk-messenger-react' does not have a declaration file. 'c:/develop/eachblock/aquatrack/management-tool-app ...

How do I access the current state in Ngrx Store without the need to subscribe, specifically for use in a route Resolve?

Presently, my Resolve implementation is quite straightforward: export class UserResolve implements Resolve<any>{ constructor(private userService: UserService){} resolve(route: ActivatedRouteSnapshot){ return this.userService.get(route. ...

Creating a function that can have either one or two arguments, with the types of the arguments determined by a specific string literal

I am looking to create a function called emitEvent(event, extra?), which will be restricted by a string literal enum of known strings such as POPUP_OPEN and POPUP_CLOSED. The function will accept a second argument that is a specifically defined dictionary ...

Retrieve the most recently added child from the Firebase cloud function

Seeking assistance in retrieving the most recently added child in a cloud function. Below is the code snippet I am using and I'm curious if there is a specific function or query I can utilize to achieve this task without having to iterate through each ...

Radio buttons do not properly switch options when used with a formControl

My FormBuilder form has two elements, a and b, defined as part of it. constructor ( private fb: FormBuilder ) { this.form = fb.group({ a: '', b: '' }); } I have four radio buttons on the template, which are displayed lik ...

Issue: Missing Router Provider! Working with angular-cli and the most recent version of @angular/router (3.0.0-beat.2)

Trying to get my angular 2 project up and running using @email protected with the --mobile flag, but encountering an error every time I attempt to launch the local server. {PROJECT_NAME}/tmp/broccoli_type_script_compiler-cache_path-3pQ1Aw4o.tmp/src/app/ap ...

Authentication using SPA RSA 2048 encryption technology

For my current project involving Angular SPA development, the customer has requested the use of RSA 2048 for authentication. I'm uncertain about how the authentication token will be generated. My understanding is that the token should be created on th ...

Pass along a JSON array from Express to Angular2

I have been working on sending a custom array filled with mongoose errors, and I am successfully creating the array. Below is the code snippet: student.save(function(err, student) { if(err) var errors = []; for (field in err.errors) { ...

Validating Firebase data for null values

Hey there, I'm currently working on a simple coding project but seems to be encountering some roadblocks. The main objective of the code is to determine if a username exists in the system or not. Here's a snippet of the data structure and codes ...