Ways to successfully transfer values or variables from within onAuthStateChanged

Currently, I am attempting to retrieve the authenticated user's uid from Google authentication for a specific collection in the "User" document. To ensure that the data does not become null after refreshing the webpage, I am utilizing onAuthStateChanged. The code snippet is provided below:

import { getDoc, doc } from 'firebase/firestore'
import { onAuthStateChanged } from 'firebase/auth'

let UserUid = ""

onAuthStateChanged(auth, (user) => {
    if (user != null) {
        UserUid = user.uid
    }
    else {
        console.log("User is null")
    }
})

const docSnap = await getDoc(doc(db, "User", UserUid))

interface DataUser {
    FullName: string;
    Email: string;
    ContactNo: string;
    CountryCode: string;
    ICNO: string;
    HomeAddress: string;
    image: string;
    userType: UserType;
}

export const DataUser:DataUser = {
    FullName: docSnap.data()!["Name"],
    Email: docSnap.data()!["Email"],
    ContactNo: docSnap.data()!["Contact"],
    CountryCode: docSnap.data()!["CountryCode"],
    ICNO: docSnap.data()!["ICNO"],
    HomeAddress: docSnap.data()!["HomeAddress"],
    image: docSnap.data()!["Image"],
    userType: 0,
}

An error has been encountered where the last line displays an empty string for UserUid. It appears that the value is not being passed to UserUid from onAuthStateChanged.

Is there a way to successfully pass the value to UserUid?

I attempted using this.UserUid, but it returned an error stating that this was undefined.

Answer №1

Upon the initial page load, there is no current user present as Firebase must verify with the server if the credentials are still valid, which can cause a delay.

Your main code cannot be made to pause until this verification process is complete. Therefore, you must handle this scenario by displaying a "loading..." message. Once the user's credentials have been verified, you can proceed with executing the necessary code that requires the UID - triggering it within the onAuthStateChanged function.

Answer №2

By utilizing localStorage.[custom_name], I successfully resolved the issue at hand.

onAuthStateChanged(auth, (user) => {
    if (user) {
        localStorage.useruid = user.uid
    }
    else {
        console.log("User is Log Out")
    }
    
})

// The user's unique identifier remains on the webpage even after reloading.
console.log(localStorage.useruid)

const docSnap = await getDoc(doc(db, "User", localStorage.useruid))

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

Contrasts between importing libraries in angular.json vs. within a component

When trying to import jQuery into my Angular 7 application, I discovered that there are two different methods to accomplish this task. The first method involves adding the jquery.min.js file to the scripts property in the angular.json file. Alternatively ...

Prioritizing tasks, always giving a call once they are completed

I am trying to populate an HTML snippet with data from Firebase. Here is the JavaScript code I wrote to achieve this: members.forEach(el => { console.log(el) table_number++; console.log("forEachMember" + table ...

What is the correct way to interpret JSON data received from an Ajax response?

Here is the code snippet that I used: axios.get(url).then(result => { this.setState({ list: result.data, }); }) .catch(e => { console.log("Some error occurred", e); }); The constructor in my code looks like this: constructor(pro ...

Utilize the Typescript model in the form of an Array structure

I have created some models and I need to use the type that will be assigned as an array. After receiving a result from an api call, I instantiate a new object of my 'type', but the result is an array. How can I make this work? When I set the var ...

performing resolver when needed in angular version 5

I have been working on a project using Angular and recently updated it from version 4.2 to Angular 5. Although I haven't utilized any new features introduced in Angular 5 yet. My current task involves executing a resolver on a specific route when a c ...

Declaring an array that holds Angular components in Angular 11: What's the best approach?

I'm trying to implement a feature in my Angular component where I can create a list that displays content from other components. My current approach involves declaring an array that contains references to different Angular components: import { Compone ...

What is the best way to extract a value from an input within a filter?

I am currently utilizing ngx-easy-table in my application. I am trying to retrieve the input filter value on keyup event, but I have not been able to find any helpful information in the documentation. Does anyone have any insights or suggestions on how to ...

Enhancing Request JSON Body Validation in Next.js 14 API Handler

I'm currently in the process of developing an API for my iOS application using Next.js 14. I have managed to get it up and running successfully, however, I am facing some challenges when it comes to properly validating the body of a request. ESLint is ...

The variable 'x' is being referenced before being initialized

Having trouble understanding the tsserver error in this static method from the Logger class. LogLevel const enum LogLevel { ERROR = 0, WARN = 1 } export default LogLevel; Logger static defaultHandler(level: LogLevel, ...message: readonly ...

The formio onchange event may result in an undefined object

Encountering an issue here: Error: src/app/app.component.html:1:30 - error TS2532: Object is possibly 'undefined'. 1 <form-builder [form]="form" (change)="onChange($event)"></form-builder> while working on my for ...

What is the ideal timing to incorporate an error handler in an Observable?

I find myself uncertain about the best practices for error handling in general. For instance, if I'm already handling errors in my service using catchError, is it necessary to also include an error handler in my subscription? Here's an example o ...

Postponed attaching event listeners to a Vue 3 instance within an iframe

Due to a specific requirement, I find myself in need of running a Vue instance inside an iframe. After some research and adjustments based on this thread from the Vue forum, I was able to achieve this goal while adapting the code for Vue 3 and removing unn ...

Achieving CommonJS imports compilation with Typescript

In my TS file, I've included a 3rd party package using import XXX { YYY, ABC, 123 } from 'XXX'; While it compiles to CommonJS without any issues, I'd prefer to have it compiled to an ESModule instead. I tried changing the target and mo ...

Finding the ID of the element that was clicked with strict typing

Consider a scenario where we aim to record the ID attribute of a clicked element using the TypeScript code snippet below: onClick(event) { console.log(event.target.attributes.id.nodeValue); } The function above takes the clicked object as an argument, h ...

Is there a syntax available for type annotation of arrays created from pre-declared variables?

According to my standards, all possible annotations are required in TypeScript. Therefore, TypeScript-ESLint is prompting me to annotate the `[ responseData, cognitoUser ]`. However, when I try to use the syntax `[ responseData1: ResponseData1, responseD ...

Best Practices for Integrating Angular with Your Custom JavaScript Library

Imagine needing to create a TypeScript function that can be utilized across various components, services, or modules. For example, let's say you want an alert wrapper like this: my_alert(msg); // function my_alert(msg) { alert(msg); } You might hav ...

Experiencing difficulty in transferring array information from a parent component to a child component within an

I'm currently working on a task where I need to pass data from a parent component to a child component. The data consists of an array that is nested within another array. parent.component.html <div *ngFor="let parent of parentArray; index as ...

Creating an array dynamically based on the attributes of an Angular component

I am looking to automatically display a table based on the inputted data. I want to assign a value to each state line within the state object, such as state.Q0, state.Q1, state.Q2. Additionally, I would like each cell to be automatically given a unique i ...

One-liner in TypeScript for quickly generating an object that implements an interface

In Typescript, you can create an object that implements an interface using a single expression like this: => return {_ : IStudent = { Id: 1, name: 'Naveed' }}; Is it possible to achieve this in just one statement without the need for separate ...

Using Ionic2, include NavController into Injectable Service

Having an issue with an Injectable Service in Angular2 with Ionic2 framework. Here is how my service is structured: import {Injectable} from '@angular/core'; import {NavController} from 'ionic-angular'; @Injectable() export class Vie ...