Error message: When attempting to access firebase data in our app, an uncaught TypeError is thrown, stating that it is unable to read properties of undefined while trying to access '

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>

https://i.sstatic.net/53cnZqeH.png

Answer №1

When working with script setup, it is crucial to utilize .value in order to modify the variable's value. The code snippet provided demonstrates an issue where the user update is done directly without utilizing .value.

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

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

Looking for a Regex pattern for this example: 12345678/90 MM/DD/YYYY

I am having success with the first 10 digits spaced apart, but unfortunately my date regex is not working as expected. ^(\d{6}\s{2}|\d{8})\/(\d{1}\s|\d{2})\s\/(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))&bso ...

What is the best way to generate an array from JSON data while ensuring that the values are not duplicated?

Upon receiving a JSON response from an API, the structure appears as follows: { "status": "success", "response": [ { "id": 1, "name": "SEA BUSES", "image": null }, { "id": 2, ...

Utilizing React Native to dynamically generate buttons through a loop

I am currently working on retrieving data from the Eventbrite API. The information I am hoping to extract is the event names, which will then be added to a list. Within the render function, I aim to dynamically create buttons based on the number of event ...

Tips for revealing a link after the user clicks on the submit button

I am looking to set up a webpage that will display a hyperlink after the submit button is clicked. For example, 1) wedding 2) engagement 3) birthday All three items are checkbox buttons and there is a textbox to input the budget. After clicking the sub ...

Executing asynchronous jQuery AJAX requests using the async/await syntax

Currently, I have a situation where I am using 3 ajax call methods in succession. However, there needs to be a delay between the second and third ajax calls. Initially, I used "async:false" in the second ajax call and everything worked smoothly. But later ...

Executing Datalist's Delete Command through Page Methods Implementation

Recently, I came across an issue with my DataList and Update Panel on my webpage. I noticed a significant delay in response time after incorporating the Update panels... intrigued, I delved deeper into this phenomenon and found some interesting insights in ...

Steps for organizing an array based on unique requirements

My goal is to retrieve an array that consists of the first and second objects based on the "point" property of each object I have a specific condition where if it is satisfied, the positions will be swapped. Default: ENGLISH[0] ENGLISH[1] MATH[0] MATH[1] ...

Why does my chart.js disappear every time I perform a new render?

Hey there, I'm facing an issue with my code. Let me paste what I have... import React, { memo, useEffect } from 'react'; import Chart from "chart.js"; /* redux-hook */ import { useSelector } from 'react-redux' const lineChart = m ...

Tips for incorporating asynchronous requests within a firestore .forEach iteration?

Currently, I am utilizing the Firebase admin SDK server-side functionality. In a specific route, I retrieve a collection and then iterate over each document within that collection. Within each iteration, I utilize a property value to perform a secondary ge ...

Ways to transfer a v-model from the parent component to a template

I'm currently in the process of designing the user interface for a search page and I want to utilize components to help with code reusability. However, I am facing a challenge in figuring out how to pass the model of the page to the search component. ...

Unexpected issue: Router component in Vuejs not receiving prop after page reload

Lately, I've come across a Vue router issue. Let's consider a scenario where we have a Vue CLI project with an App component structured as follows: <template> <div id="app"> <div class="links"> &l ...

What is the ideal format for an AJAX request that includes sections for handling success and error scenarios?

When making AJAX calls for CRUD operations in MVC, I often find myself unsure about the standard or most common usage of the complete, success, and error functions. Some examples show these functions without any parameters, while others include parameter ...

Is there a way to ensure that a certain block of code in Typescript is executed only after an API call has been completed?

When making an API call, I need the code after the call to wait until the API call finishes. In my function called this.api_call, it calls the API and only returns an array returnValue once the call is complete. let returnValue = this.api_call(data); // ...

Enhancing the default vue-cli webpack app with additional components

To ensure reproducibility, I began by setting up a basic project using vue-cli: npm install -g vue-cli vue init webpack spa cd spa npm install npm run dev Afterwards, I decided to swap out the Vue logo with an app-header component. Here's how I impl ...

Invoke a CoffeeScript function within a jQuery function

Two files are causing me trouble: one is written in plain jQuery, and the other is a Coffeescript The jQuery file looks like this: $(document).ready(function(){ checkPrice(); }); In comparison, the CoffeeScript file appears as follows: $ -> c ...

The synergy between ES6 arrow functions and array mapping techniques

I'm currently exploring shorthand methods of writing ES6 code and I've come across an example that has left me puzzled. The last shorthand used, "({length})", retrieves the length property of an array. While I understand how it works in this cont ...

Uh-oh, Ajax encountered a 500 Internal Server Error!

Utilizing ajax to fetch events from my database has hit a snag. Instead of displaying the results, there is nothing visible on the screen, and the console is showing this error message: POST http://www.example.com/system/live_filter.php 500 (Internal Se ...

Is there ample documentation available for Asp.Net Ajax controls?

Struggling to locate the client side functionality of Asp.net Ajax controls such as calendarextender. How can I determine the specific client side functionalities of each control or Calendar control? So far, I have only discovered the properties ._selected ...

Scrolling without limits - cylindrical webpage (CSS/JS)

Is it possible to create a page that infinitely scrolls from top to top without going straight back to the top, but instead showing the bottom content below after reaching it? Imagine being able to scroll up and see the bottom above the top like a 3D cylin ...

The specific module 'franc' does not have the export named 'default' as requested

Every time I attempt to use the franc package, I encounter the following error message: "The requested module 'franc' does not provide an export named 'default'." Unfortunately, I am unsure of what this means, despite trying to resolve ...