Is there a way to store a Firebase 9 onAuthStateChanged user object within a Vue ref?

I have implemented Firebase 9 in my Vue 3 / Quasar / TypeScript application.

Below is the getUser.ts composable used to retrieve the user from Firebase:

import { ref } from 'vue';
import { auth } from 'src/firebase/config';
import { User, onAuthStateChanged } from 'firebase/auth';

const user = ref<User | null>(auth.currentUser);

console.log('user.value in getUser', user.value); // <-- This returns null

onAuthStateChanged(auth, (_user) => {
  user.value = _user;
  console.log('user.value in getUser onAuthStateChanged', user.value); // <-- This returns a valid user object
});

const getUser = () => {
  return { user };
};

export default getUser;

In addition, here is my Pinia store named user.ts:

import { defineStore } from 'pinia';
import { LocalStorage } from 'quasar';
import useUser from 'src/composables/useUser';
import getUser from 'src/composables/getUser';
import getDocument from 'src/composables/getDocument';
import { User } from 'src/types';

const { updateUserProfile } = useUser();
const { user } = getUser();

console.log('user.value in user store', user.value); // <-- This returns null

let userObject = {};
if (user.value) {
  const { document: userDocument } = getDocument('users', user.value.uid);
  userObject = {
    firstName: userDocument.value?.firstName as string,
    lastName: userDocument.value?.lastName as string,
    displayName: user.value.displayName,
    photoURL: user.value.photoURL,
    email: user.value.email,
    phoneNumber: user.value.phoneNumber,
    uid: user.value.uid,
  };
}

const useUserStore = defineStore('user', {
  state: () => ({
    user: (LocalStorage.getItem('user') || userObject) as User,
  }),
  actions: {
    async setPhotoURL(photoURLData: string | undefined) {
      await updateUserProfile({ photoURL: photoURLData });
      this.user.photoURL = photoURLData;
    },
    setEmail(emailData: string) {
      this.user.email = emailData;
    },
    setPhone(phoneNumberData: string) {
      this.user.phoneNumber = phoneNumberData;
    },
  },
});

export default useUserStore;

The user.value being used within onAuthStateChanged accurately reflects the Firebase user object. However, the other instances of user.value always show null values.

What could be causing this discrepancy?

Answer №1

If you're looking for a solid demonstration of utilizing Firebase v9 alongside Vue 3 and TypeScript, this resource is an excellent reference point. The relevance of Quasar in this context is negligible.

For additional insights, check out the repository at: https://github.com/oless/firebase-v9-typescript-example

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

Observing nested objects in Vue while utilizing deep watching功能

Is there a way to determine which property change in the object triggered the watch call while watching a data object with multiple properties using deep invocation? data(){ return { user:{ first_name:'', last_na ...

Create a "load additional data" button

I'm working on building my blog and I've run into a roadblock while trying to implement a load more button. Here's what I currently have: actions: { LOAD_ARTICLE_LIST: function ({ commit }) { axios.get('someurl/articles') ...

Updating component data in VueJS can sometimes be tricky, especially when dealing with the same

I have a route called '/posts' which includes a created() function that fetches data from an API using GET and displays the data on the page. Recently, I added a navbar to all pages with an input field for searching posts by tags. This tag-based ...

Enhancing user experience with bootstrap-vue by allowing interaction with content under modal through clicking

Looking to enable the ability to click on a button or select content from the background/page while a modal is open. Came across a suggestion at: Allow people to click on links under bootstrap modal when modal backdrop is not present which advises using . ...

Implementing custom CSS styles for HighCharts API pie chart drilldown labels

I successfully created a pie chart using highcharts and configured the chart with the following options: chart: { type: 'pie', }, In order to change the width of the text on the chart, I added the following options which force e ...

What is causing the data not to react with the props in this particular scenario?

In addition to the central App.vue component, I have two other components - Rooms.vue and Desks.vue. When a swiper element in the Rooms.vue component is clicked, it triggers the opening of the Desks.vue component and emits the room object to App.vue. This ...

Arrays in Vue Data

After creating an array and pushing data into it, the array turns into a proxy, preventing me from using JavaScript array functions on it. export default { name: 'Home', components: { PokeList, FilterType, SearchPokemon}, data() { r ...

Discover the steps to dynamically set global data in Vue during runtime

I am currently working on a Vue application that requires fetching data from JSP at runtime, which means I cannot use .env files. As a solution, I am attempting to set data in Vue that can be accessed throughout the entire application (components, mixins, ...

What is the connection between tsconfig.json and typings.json files?

I recently acquired a .NET MVC sample application that came with Angular2-final. Within the project, I noticed a typings.json file at the root and a tsconfig.json file in the ng2 app directory. What is the connection between these two files? Is this the mo ...

IntelliSense for TypeScript Variable Names in Intellij

When declaring a variable or field in Java, it is common practice to specify the type. For example: public SomeDataType someDataType = new SomeDataType(123) As you begin typing Som.., IntelliJ's autocomplete feature will likely suggest SomeDataTyp ...

Guide on setting the focus of an input in a form field using ngIf

I am currently facing an issue where I need to focus on a specific input in my code based on certain conditions derived from an observable. In this scenario, I have initialized a boolean to true inside the ngOnInit() method. export class InputOverviewExamp ...

From TypeScript Map to Java Map: A Comparison of Map Types

I need to make a call to a Java API from my Angular 2 application. I have utilized a TypeScript Map to send the request in the Java app. The RestEndpoint in Java looks like this: @PostMapping(value = Constants.PATH_BASE + "/sync/list") public ResponseEn ...

Invoking a function on an object of a subclass that derives from an abstract class

In the realm of abstract classes, behold this one: export abstract class BaseStepComponent { /** Behold thy base-step ctor */ constructor() { } abstract getValue(): string; } And lo, here is a component that inherits such abstract glory ...

Angular - Karma Testing - Error: Unable to access property 'textContent' of undefined

I encountered an issue while running 'ng test' on my Angular 6 application: Error: Unable to access property 'textContent' of null To view a sample of the application, please check out: SampleApp The problem seems to be originatin ...

The mat-slide-toggle component does not recognize the checked binding

My angular app contains the mat-slide-toggle functionality. switchValue: {{ switch }} <br /> <mat-slide-toggle [checked]="switch" (toggleChange)="toggle()">Toggle me!</mat-slide-toggle> </div> This is how the ...

Can Typescript union be utilized to define field choices?

I am working with a type that can accept either a string or a number as options, defined like this: type Result = string | number type ValueData = { data: Result } const valueDataSchema = new mongoose.Schema({ data: { type: Result } ...

There seems to be an issue with transferring data between components in Angular

For the login feature, I am looking to receive an email using two-way databinding. ... export class LoginComponent implements OnInit { author ={ email:'', password:'' } constructor(private _auth: AuthService, private route ...

Key ConfusionUpdated descriptionKeyword confusion

What is the reason for the absence of errors in this code snippet: interface X { a: string; b?: string; } type Y<T> = { [key in keyof T]: boolean; } class A<Definition> { constructor(public readonly definition: Definition, publ ...

Combining Bootstrap Vue: utilizing class names alongside HTML tags

(Bootstrap-Vue 2.0, Vue.js 2.5) Is it possible to combine traditional CSS Bootstrap 4 classes with Bootstrap-Vue? For example, can I use the following code snippet: <section id="introduction"> <b-container class="h-100"> & ...

unanticipated redirection with Vue router

Here is the routing code snippet: // exporting for component use export var router = new VueRouter(); // defining routes router.map({ 'home': { component: Home, auth: true }, 'login': { component: L ...