A guide on retrieving data from Firestore using TypeScript

I've been diving into a chat project using Angular, and Firestore has given me a bit of trouble. Trying to get the hang of typescript while working with it.

Within app.module.ts, kicking things off with:

    import { provideFirebaseApp, getApp, initializeApp } from '@angular/fire/app';
    import { getFirestore, provideFirestore } from '@angular/fire/firestore'
    
imports: [
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideFirestore(() => getFirestore()),
],

Created a FirestoreService for data retrieval and updates.

Updates on array in documents are smooth sailing, but querying Firestore has me puzzled - always ending up with undefined results.

import { AngularFireAuth } from '@angular/fire/compat/auth';
import {
  Firestore,
  getFirestore,
  provideFirestore,
  collectionData,
  collection,
  doc,
  getDoc,
  docData,
  query,
  setDoc,
  updateDoc,
  addDoc,
  firestoreInstance$,
  DocumentData,
  arrayRemove,
} from '@angular/fire/firestore';

// More code followed by a rejection method...

async rejectFriendRequest(rejectedUser: string, currentUser: string){
    const recipientRef = doc(this.firestore, "users", JSON.stringify(currentUser));

    await updateDoc(recipientRef, {
      invitationsFrom: arrayRemove(rejectedUser),
      rejectedInvitation: arrayUnion(rejectedUser)
    });
  }

The rejection method is doing its job updating arrays in specific documents. However, reading documents from Firestore has hit a roadblock, unsure about which library to use next. The initial idea was to use email addresses as document IDs, but faced issues when needing to update an ID containing a ".".

One of my attempts involved this snippet:

async getUser(id: string) {

    var usersRef = this.aF.collection("users").doc(id);

    var colRef = collection(this.firestore, "users")
    var docreference = await doc(colRef, id);

    docData(docreference).subscribe( (result) => {
      console.log(result);
    })

  }

Answer №1

In order to monitor changes in the document, it is essential to set the document reference and use the valueChanges() method on that reference within your constructor. This will allow you to create an update method that can modify the item reference as it undergoes changes.

This approach is beneficial as it enables all methods to access it via this. You can refer to this Official example docs for more information.

import { Component } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/compat/firestore';
import { Observable } from 'rxjs';

export interface Item { name: string; }

@Component({
  selector: 'app-root',
  template: `
    <div>
      {{ (item | async)?.name }}
    </div>
  `
})
export class AppComponent {
  private itemDoc: AngularFirestoreDocument<Item>;
  item: Observable<Item>;
  constructor(private afs: AngularFirestore) {
    this.itemDoc = afs.doc<Item>('items/1');
    this.item = this.itemDoc.valueChanges();
  }
  update(item: Item) {
    this.itemDoc.update(item);
  }
}

To view information with minimal adjustments in your specific scenario, you should consider something like:

const itemDoc = this.firestore.doc(`users/${documentId}`);
const item = itemDoc.valueChanges();
console.log('item', item);

The presence of the second Firestore defined in your constructor seems out of place, so I recommend reviewing more examples.

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

How can you establish a TypeScript project that employs classes shared by both client and server applications?

I am working on a project that consists of two components: ServerApp (developed with nodejs using NTVS) and BrowserApp (an Html Typescript application). My goal is to share classes between both projects and have immediate intellisense support. Can you pr ...

Discovering the object and its parent within a series of nested arrays

Is there a way to locate an object and its parent object within a nested array of unknown size using either lodash or native JavaScript? The structure of the array could resemble something like this: name: 'Submodule122'

I have been using ...

When the meta tag content "&" is used, it will be converted to "&amp;" in the final output

In my Nextjs webapp, I am utilizing Firebase to store images. The URI contains the "&" sign that is being converted to "&" inside the Head component. For instance, if I create a simple tag like this <meta property="test" content="& ...

Building a resolver to modify a DynamoDB item via AppSync using the AWS Cloud Development Kit (CDK)

After successfully creating a resolver to add an item in the table using the code provided below, I am now seeking assistance for replicating the same functionality for an update operation. const configSettingsDS = api.addDynamoDbDataSource('configSet ...

Expanding external type declarations within Typescript

I am currently working with Typescript and the ant design library. My goal is to extend an existing interface by adding a single property. To start, I imported the original interface so you can see the folder structure: import { CollapseProps } from &apo ...

Why does my component in React-Firebase keep triggering an unlimited number of console.log calls?

Currently, I am working on a project using React and Firebase as the backend. In my development process, I encountered an issue where I needed to pass authenticated user details from the GigRegister component to the UniqueVenueListing component through pro ...

Assign a true or false value to every attribute of an object

Imagine we have a scenario with an interface like this: interface User { Id: number; FirstName: string; Lastname: string; Age: number; Type: string; } and a specific method for copying properties based on a flag. ...

Managing Data Types in a React and Express Application

I am working on a project that includes both a React client and a Node-Express backend. Currently, my React app is running with TypeScript and I am looking to switch my backend to TypeScript as well. At the moment, my project structure consists of a clien ...

I am currently struggling with a Typescript issue that I have consulted with several individuals about. While many have found a solution by upgrading their version, unfortunately, it

Error message located in D:/.../../node_modules/@reduxjs/toolkit/dist/configureStore.d.ts TypeScript error in D:/.../.../node_modules/@reduxjs/toolkit/dist/configureStore.d.ts(1,13): Expecting '=', TS1005 1 | import type { Reducer, ReducersMapO ...

Does the Firestore onCreate trigger include the most up-to-date data or just the data that was submitted at the time of

Currently, I am implementing a commenting system and need to keep track of the number of comments being made. One approach I am considering is using the onCreate trigger to update the comment count every time a new comment is created. I am aware that the ...

Unable to resolve all parameters for the RouterUtilities class

My goal is to develop a RouterUtilities class that extends Angular's Router. Despite the app running and compiling smoothly, when I run ng build --prod, it throws an error message like this: ERROR in : Can't resolve all parameters for RouterUtil ...

Compelled to utilize unfamiliar types in TypeScript generics

When working with a Typescript React form builder, I encountered a situation where each component had different types for the value and onChange properties. To tackle this issue, I decided to utilize generics so that I could define the expected types for e ...

What is the process for incorporating a standalone custom directive into a non-standalone component in Angular?

Implementing a custom directive in a non-standalone component I have developed a custom structural directive and I would like to use it across multiple components. Everything functions as expected when it is not standalone, but encountering an error when ...

Dissimilarities in behavior between Angular 2 AOT errors

While working on my angular 2 project with angular-cli, I am facing an issue. Locally, when I build it for production using ng build --prod --aot, there are no problems. However, when the project is built on the server, I encounter the following errors: . ...

Ways to display all current users on a single page within an application

I have come across a project requirement where I need to display the number of active users on each page. I am considering various approaches but unsure of the best practice in these scenarios. Here are a few options I am considering: 1. Using SignalR 2. ...

The Mat table is not updating on its own

I am facing an issue in my Angular application where a component fetches a hardcoded list from a service and subscribes to an observable to update the list dynamically. The problem arises when I delete an element from the list, as it does not automaticall ...

Creating a unique custom selector with TypeScript that supports both Nodelist and Element types

I am looking to create a custom find selector instead of relying on standard javascript querySelector tags. To achieve this, I have extended the Element type with my own function called addClass(). However, I encountered an issue where querySelectorAll ret ...

Can you provide guidance on how to access my account using the code that I have?

I'm having trouble getting the login functionality to work properly with this code. When I click the login button, nothing happens - no errors are displayed either. Can you help me identify what might be causing this issue? login() { var url = &ap ...

Utilizing Variables in TypeScript to Enhance String Literal Types

Here are my codes: export const LOAD_USERS = 'LOAD_USERS'; export const CREATE_USER = 'CREATE_USER'; export interface ACTION { type: string, payload: any } I am trying to limit the possible values for ACTION.type to either 'L ...

Submitting the form leads to an empty dynamically added row

I am currently working on a gender overview that allows you to edit, add, or delete genders using a simple table. The functionality of adding and deleting rows is already implemented. However, I am facing issues with displaying the correct web API data as ...