How can I retrieve the document id from Firestore using Angular?

I attempted to generate an auto document ID in Firestore and retrieve the document ID in Angular 8 using the code provided. However, I am encountering an issue where I only receive the document ID after the execution has been completed. Can someone please assist me with this? Thank you in advance.

        this.db.collection("testdata2").add({
        "name": "Tokyo",
        "country": "Japan",
        "Date": this.date
        })
        .then(function(docRef){ 

          component.docid=docRef.id;
          console.log("Document written with ID: ", docRef.id); 

        })
        .catch(function(error) {
          console.error("Error adding document: ", error);
        });
        console.log(component.docid);

Answer №1

Using promises in your code means that the callbacks inside then and catch will be executed after everything else has completed. In this scenario, they will run after the final console.log(component.docid). To simplify the process, you can declare your method as async (refer to MDN's async function guide). Your updated code would then appear as follows:

try {
    const docRef = await this.db.collection("testdata2").add({
        "name": "Tokyo",
        "country": "Japan",
        "Date": this.date
    });

    component.docid = docRef.id;
    console.log("Document written with ID: ", docRef.id); 
} catch (error) {
    console.error("Error adding document: ", error);
}
console.log(component.docid);

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

Is there a way for me to retrieve the bodyHeight attribute of ag-grid using public variables or data?

Working on a project using ag-grid community react. The main feature is a scrollable section filled with data, which can range from one piece to millions of pieces. I'm also incorporating a footer component for the grid that needs to adjust its height ...

The data type 'null' is not a valid index type to be used in the Array.reduce() accumulator

This is a follow-up inquiry from: How can JavaScript convert multiple key-value pairs in object lists into one nested object? The initial objective was to merge numerous objects with various key-value pairs into a single nested object. For example, start ...

Obtain the filter criteria within the user interface of a Kendo grid

My Kendo grid looks like this: <kendo-grid [data]="gridData" [pageSize]="state.take" [skip]="state.skip" [sort]="state.sort" [filter]="state.filter" filterable="menu" (dataStateChange)="dataStateChange($event)" > In the ...

Having trouble moving to a different component in Angular?

In my application, I am facing an issue with navigating from List to Details component by passing the ID parameter. It seems that there is no response or error when attempting to call the relevant method. Below, you can find the code snippets related to th ...

Using Angular 2 to assign a function to the ngClass directive within the template

I've been searching for a solution to this issue, but so far nothing has worked for me. When I try to pass a function to the ngStyle directive, I encounter the following error: The expression 'getClass()' in ProductView has changed after i ...

Error encountered in lodash.js in Angular 2 framework

I have been attempting to implement lodash for a datatable. Here are the steps I followed: First, I tried running npm install lodash, but encountered an error stating that the package could not be found After researching the issue, I attempted npm in ...

How to Add External Applications Using Angular-CLI

I am a newcomer to using angular-cli and I have a question regarding the installation of the npm library mdbootstrap. Following the guidelines provided here in the Angular CLI Instructions, I attempted to install mdbootstrap by executing the following step ...

Exploring the possibilities of ZMQ_XPUB_MANUAL in action with zeromq.js

I'm currently in the process of setting up a pub/sub broker using ZeroMQ, and I want to ensure that clients are only able to subscribe to authorized prefixes. While researching this topic, I came across a helpful tutorial that discusses achieving a si ...

Is it advisable to encapsulate my entire Express server within a TypeScript class?

After working extensively with nodeJs, I have decided to explore developing applications in Typescript. Recently, I came across various blogs (like this one) that recommend wrapping modules and the app's entry point in a class when creating a RESTful ...

Utilizing TypeScript code to access updatedAt timestamps in Mongoose

When querying the database, I receive the document type as a return. const table: TableDocument = await this.tableSchema.create({ ...createTableDto }) console.log(table) The structure of the table object is as follows: { createdBy: '12', cap ...

What is the best way to pass the answerId in the action that I am dispatching, when the answerId is nested within an array object within another array object in

Reflect on the following: private listenToAnswerDeleted() { this.uiService.onGlobalEvent('ANSWER_DELETED').subscribe((response) => { this.store.dispatch(deleteAnswerAction({'answerId': })); }); } Upon receiving a respon ...

Utilize React Hook Form to easily reset the value of an MUI Select component

I created a dropdown menu where users can select from "Item 1", "Item 2", and "Item 3". Additionally, there is a "Reset" button that allows users to clear their selection and make a new one. Below is the code I used: import React from ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

Sort the array based on the enum name rather than its value

Below is an example of an enumeration: export enum Foo { AA = 0, ZZ = 1, AB = 2, ER = 5 } In my case, I want to sort my Bars based on the name of the enum (AA, AB, ER, ZZ), rather than the numerical value (0, 1, 2, 5) that they represent. ...

What is a more organized approach to creating different versions of a data type in Typescript?

In order to have different variations of content types with subtypes (such as text, photo, etc.), all sharing common properties like id, senderId, messageType, and contentData, I am considering the following approach: The messageType will remain fixed f ...

Issue with ngFor displaying only the second item in the array

There are supposed to be two editable input fields for each section, with corresponding data. However, only the second JSON from the sample is being displayed in both sections. The JSON in the TypeScript file appears as follows: this.sample = [ { "se ...

Utilizing and transmitting contextual information to the tooltip component in ngx-bootstrap

I am currently working on integrating tooltips in ngx-bootstrap and trying to figure out how to pass data to the ng-template within the tooltip. The documentation mentions using [tooltipContext], but it doesn't seem to be functioning as expected. Belo ...

Tips for setting up a personalized preview mode in Sanity Studio using Next.js

I am facing an issue displaying the preview mode because the URL must contain specific parameters such as "category" and "slug" (as shown in the image below). Here is the error URL with undefined parameters Therefore, I am unable to retrieve the paramete ...

Creating a dynamic form in Angular based on user input

I am in the process of creating a dynamic web form where the user's input will determine the subsequent form inputs that are generated. For example: <mat-form-field> <mat-select placeholder="Type" [(ngModel)]="row.Type" (change)="Typ ...

Is it possible for the Observable call in Angular 4 to function similarly to jQuery's synchronous AJAX method?

As I have a business logic function that needs to use HttpGet and I must wait for the result before continuing, jQuery's ajax can handle this easily. But I am curious if Observables have a similar feature? I was hoping for the result to be: John An ...