0

I am using Firebase 9 in my Vue 3 / Quasar / TypeScript app.

This is the getUser.ts composable I use to get 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;

And this 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 inside onAuthStateChanged correctly populates with the Firebase user object. But the other user.value refs always return null.

What am I doing wrong?

TinyTiger
  • 1,801
  • 7
  • 47
  • 92
  • Can you try refactoring the getUser function as explained in this answer? https://stackoverflow.com/questions/69875003/firebase-onauthstatechanged-always-returning-undefined Essentially use onAuthStateChanged and return a promise – Dharmaraj Feb 13 '22 at 04:49
  • @Dharmaraj I can't get that to work because I don't know how to await checkAuthState before adding it to the store. The empty store always runs before the await has finished. Mind posting an answer of how to get it to work with Pinia? – TinyTiger Feb 13 '22 at 23:48

1 Answers1

-2

Here is a great example of how to use Firebase v9 with Vue 3 with TypeScript. Quasar is irrelevant for this issue.

https://github.com/oless/firebase-v9-typescript-example

Oles
  • 1