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?