We are unable to update the document in AngularFire as the document reference ID could not be retrieved

I am currently working on an update function that is designed to retrieve a specific document based on its unique document uid, which is connected to the authenticated user's uid.

In another part of my code, I have a function that successfully fetches data from the collection using a similar method. However, when attempting to store the uid as a variable in a different function, it returns as [object object].

This function is what I use to retrieve the current user's data:

this.user$ = this.afAuth.authState.pipe(
  switchMap(user => {
    if (user) {
      return this.afs.doc<any>(`users/${user.uid}`).valueChanges();
    } else {
      return null;
    }
  })
);

This allows me to access the required fields by simply calling something like user.username.

However, when trying to store the document uid:

this.userID = this.afAuth.authState.pipe(
  switchMap(user => {
    if (user) {
      this.userID = user.uid;
    } else {
      return null;
    }
  })
); 

The value of my userID ends up being just [object object].

When I call the following:

updateUser(user: User) {
    this.userDoc = this.afs.doc(`users/${this.userID}`);
    this.userDoc.update(user);
  }

I receive an undefined document path of .../documents/users/[object Object].

So, how can I properly trace the document ID in order for the update to work correctly?

Answer №1

Modify the following:

this.userID = this.afAuth.authState.pipe(
  switchMap(user => {
    if (user) {
      this.userID = user.uid;
    } else {
      return null;
    }
  })
); 

to this:

this.userID = this.afAuth.authState.pipe(
  switchMap(user => {
    if (user) {
      this.userIDs= user.uid;
    } else {
      return null;
    }
  })
); 

A different variable name, this.userIDs, should be used to store the user.uid

Answer №2

The problem arises from the fact that both the value and the subscription to this.userID are being stored simultaneously. To resolve this issue, eliminate the assignment:

this.userID = this.afAuth.authState
. This will ensure proper storage! Instead, create a separate variable to store the subscription, which can be unsubscribed from when necessary:

this.mySubscription = this.afAuth.authState.pipe(
  switchMap(user => {
    if (user) {
      this.userID = user.uid;
    } else {
      return null;
    }
  })
);

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

"Enhance your PrimeVue Tree component with interactive action buttons placed on every TreeNode

Details: Using Vue 3.3.6 in composition API script setup style Utilizing PrimeVue 3.37.0 and PrimeFlex 3.3.1 Implemented with Typescript Objective: To create a tree structure with checkboxes that are selectable, along with action buttons on each TreeNod ...

The issue I'm facing with my webpack-build is the exclusive appearance of the "error" that

Hey everyone! I'm currently facing an issue with importing a module called _module_name_ into my React project, specifically a TypeScript project named react-app. The module was actually developed by me and it's published on npm. When trying to i ...

The type of the object is classified as 'unknown' (2571) while utilizing the map() function with an array containing objects

After researching this error extensively on Google and reading multiple posts, I am still unable to find a solution. I am trying to fetch data from an external API call that has the following signature: const properties: { [x: string]: unknown;} | { [x: s ...

Create an interactive slider using only images in an Ionic Angular content display

I need help transforming the images from WordPress into a slider instead of showing them individually. How can I achieve this? <ion-content padding> <div *ngIf="selectedItem" class="selection"> <h2 [innerHTML]="selectedItem.title.rend ...

Performing Batch Writes in Firestore using the Admin SDK

I have a massive ASCII flat file containing 1.5 million lines, which is essentially a list of parts from a manufacturer. I want to store this data in Firestore. Originally saved as a .csv file, the size was 250GB. After converting it to a JSON file using ...

The 'items' property cannot be linked to 'virtual-scroller' as it is not a recognized attribute

I'm currently facing an issue with integrating virtual scroll into my Ionic 4 + Angular project. Previously, I relied on Ionic's implementation of virtual scroll (ion-virtual-scroll) which worked well initially. However, I encountered a major dr ...

Having trouble applying CSS while printing using the ngx-print library in Angular 14. Can anyone help me out with this issue

The table shown in the image is experiencing issues with applying CSS properties when printing. While the background graphics feature has been enabled, the preview section still does not reflect the CSS styling. What could be causing this discrepancy? Cli ...

Troubleshooting: Vue and TypeScript Components Not Communicating

Vue is still fairly new to me and I'm struggling with this issue. Despite following code examples, my implementation doesn't seem to be working correctly. The component I defined looks like this: <template> <div class="row"> ...

Angular 2 - retrieve the most recent 5 entries from the database

Is there a way to retrieve the last 5 records from a database? logs.component.html <table class="table table-striped table-bordered"> <thead> <tr> <th>Date</th> <th>Logging ...

Troubleshooting Angular Karma Testing: Uncaught ReferenceError - Stripe not recognized

When running tests with karma, I encountered the following error: ReferenceError: Stripe is not defined Component import { Component, OnInit } from "@angular/core"; import { FormBuilder } from "@angular/forms"; import { Router } from & ...

Steps to load dynamic configuration in AngularFire2

I've been attempting to initialize angularfire2 with dynamic values, but I encounter errors when using aot. let _env = { apiKey: 'key...', authDomain: dynamicValueFromConfig, databaseURL: 'url...', ...

How to resolve the issue of checkbox not binding the value of an object field in Angular 4?

Can anyone help me with binding the field value in the current object and switching the checkbox based on its value? This is my checkbox: <label class="checkbox-inline checbox-switch switch-success"> <input #livingRoom type="checkbox" name ...

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

Dealing with various node types in a parse tree using TypeScript: Tips and Tricks

I am in the process of converting my lexer and parser to TypeScript. You can find the current JavaScript-only code here. To simplify, I have created an example pseudocode: type X = { type: string } type A = X & { list: Array<A | B | C> } ty ...

Currently, I am working with Angular 11 and encountered some errors while trying to embark on a new project

Command: ng serve Error: Cannot find module '@angular-devkit/build-angular/package.json' View details in "/tmp/ng-lQbnUK/angular-errors.log". These errors occurred when I tried to create the project: Installing packages (npm)... npm WARN depreca ...

Is there a way to create a TypeScript function that can accept both mutable and immutable arrays as arguments?

Writing the following method became quite complicated for me. The challenge arose because any method receiving the result from catchUndefinedList now needs to handle both mutable and immutable arrays. Could someone offer some assistance? /** * Catch any ...

The potential object null may lead to an absence of the 'value' property in the type 'EventTarget'

I am facing a problem that I am unable to resolve. The error in my HTML reads: Object is possibly 'null' and Property 'value' does not exist on type 'EventTarget'. HTML <select [(ngModel)]="selectedProvincia" (ch ...

A TypeScript class utilizing a static variable with the singleton design pattern

I have a query regarding the most effective way to code this scenario: Within a class, I require a static variable that is accessible throughout the entire project: connection Singleton without namespace: class Broker { static connection: Connection = u ...

The database did not respond, causing the API to resolve without sending a response for the specified endpoint (/api/dates). This could potentially lead to requests becoming stalled in Next

I have been attempting to retrieve a list of dates from my database in a straightforward manner, but unfortunately, I am not receiving any response (even after trying to log the response data to the console). The only feedback I seem to be getting when sel ...

Optimizing Angular 2+ performance with a custom minification of the

I've taken note of the cautions regarding avoiding pipes for ordering/sorting. While I understand the concerns with impure pipes, I'm not entirely clear on the issue with minification. The documentation and various posts highlight the potential ...