Search code examples
javascriptvue.jsgoogle-cloud-firestorefirebase-authentication

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'displayName') when using firebase data in app


I am using firebase 9 and vue3 and receive this error when trying to use the data from a doc. I console.log the data and it shows correctly but it states it is undefined. I have also made sure my data is loaded before trying to use it (not shown 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">Sign Out</button>
</template>

enter image description here


Solution

  • In script setup we need to use .value to make any change in the value of the variable. Here in the code shared, when updating user, you are updating it directly without .value.

    if (docSnap.exists()) {
      onSnapshot(docRef, (doc) => {
        console.log(doc.data());
          user.value = {...doc.data()};
        });
      } else {
        console.log("No document exists");
      }