While using Firebase 9 and Vue3, I encountered an error when trying to access data from a document. Even though the data was correctly logged in the console, it was showing up as undefined. Additionally, I made sure that the data was loaded before attempting to use it (not displayed below).
<script setup>
import Navbar from "@/components/navbar.vue";
import { onMounted, ref } from "vue";
import { getAuth, onAuthStateChanged, signOut } from "firebase/auth";
import { useRouter } from "vue-router";
import { doc, getDoc, onSnapshot } from 'firebase/firestore';
import {db} from "@/main.js";
const router = useRouter();
const loggedIn = ref(false);
let user = ref();
let auth;
onMounted(async () => {
auth = getAuth();
const docRef = doc(db, 'users', auth.currentUser.uid);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
onSnapshot(docRef, (doc) => {
console.log(doc.data());
user = {...doc.data()};
});
} else {
console.log("No document exists");
}
onAuthStateChanged(auth, (user) => {
if (user) {
loggedIn.value = true;
} else {
loggedIn.value = false;
}
});
})
const handleSignOut = () => {
signOut(auth).then(() => {
router.push("/")
})
}
</script>
<template>
<navbar></navbar>
<p>Account Page</p>
<div v-if="loggedIn" >Hello, {{user.displayName}}</div>
<button @click="handleSignOut"&gr;Sign Out</button>
</template>