Having trouble setting a value in a Vue.js variable

Upon assigning a value retrieved from the firebase collection, I encountered the following error message.

Error getting document: TypeError: Cannot set property 'email' of undefined at eval (Profile.vue?5a88:68)

Here is the code snippet in question.

import firebase from 'firebase';
import fb from "@/firebase";
export default {
  name: 'Upload',
  data(){
    return{
        bio: '',
        name: '',
        email: '',
        imageData: null,
        picture: 'http://ssl.gstatic.com/accounts/ui/avatar_2x.png',
        uploadValue: 0
    }
  },
  created() {
    this.setUsers();
  },
  methods:{
    setUsers: () => {
      var userRef = fb.collection("users").doc(firebase.auth().currentUser.uid);
      userRef.get().then(doc => {
        this.email = doc.data().email; 
      }).catch(function(error) {
          console.log("Error getting document:", error);
      });
    },
 }
}

Why am I encountering this particular error and what steps can be taken to rectify it?

Answer №1

the scope of 'this' may be lost within a Firebase callback function.

To access 'this' inside a Firebase callback, assign it to another variable first.

setUsers: () => {
  const instance = this
  var userRef = fb.collection("users").doc(firebase.auth().currentUser.uid);
  userRef.get().then(doc => {
    instance.email = doc.data().email; 
  }).catch(function(error) {
      console.log("Error getting document:", error);
  });
},

Answer №2

Have you attempted to access instance.email for troubleshooting purposes?

userRef.get().then(doc => {
console.log(instance.email)
})

The output should be an empty string. If it's returning undefined, that may be the source of the error.

If it's not undefined, then you need to verify if doc.data().email is present.

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

Teaching jQuery selectors to detect recently-added HTML elements

Unable to find a solution in the jQuery documentation, I am seeking help here for my specific issue. Embracing the DRY principle, I aim to utilize JavaScript to include a character countdown helper to any textarea element with maxlength and aria-described ...

Having difficulties fetching data from Express server to React

My current project involves fetching data from an Express server to a React application using the Fetch API. The Express server interacts with a PostgreSQL database to retrieve relevant data that should be sent to the React frontend. The code snippets bel ...

Utilizing Twitter API authentication to prevent hitting rate limits

Currently, I am implementing the Twitter API to showcase the most recent tweets from 4 distinct users on my webpage. It seems that once a certain number of calls are made, an error message appears stating "NetworkError: 400 Bad Request" and prevents the tw ...

The navigation bar options are not collapsing as intended

When I resize my page to width:750px;, my navigation bar is not collapsing the items. Despite trying to edit my CSS, I am still clueless. Here is my live page. This is the CSS for my slidebar: @media (max-width: 480px) { /* Slidebar width on extra small ...

Customize Text Area's Font Based on Selected Option in Dropdown List

I'm currently working on an HTML file that includes a dropdown list and a text area. Here's the code snippet: <select id='ddlViewBy' name='ddlViewBy' onchange='applyfonttotextarea()'> <option value = ' ...

When attempting to print the content inside a Bootstrap modal, the display does not appear but instead a blank page is printed

My goal is to print the text content of a bootstrap modal while leaving space for images blank when clicking the print button located within the modal. Unfortunately, upon clicking the print button, I am only getting a blank page without any content displ ...

Vue Component's computed property presentation: [Vue alert]

I recently developed a basic Vue 2 component: Vue.component('upper', { props: ['value'], template: '#upper-template', computed: { formattedValue: function() { return this.value.toUpperCase(); ...

Dynamic color changes in VueJS: Adjusting SCSS variables on the fly or dynamically importing SCSS files

I have multiple sub-Domains like example.com/abc, example.com/def, etc. all running on a single server. Each domain needs to have its own unique styling with different primary and secondary colors. I want to be able to dynamically change these colors based ...

Challenges transitioning syntax from Firebase 4 to Angularfire2 in Angular 4

Currently, I'm in the process of updating my Angular 2.3.1 and Firebase 2.x.x project to the newest version. However, I'm encountering difficulties with syntax and imports. I've been exploring resources like https://github.com/angular/angula ...

PHP dropdown menu - Retrieve data from second database and display it

Currently, I am working on a project that involves both Vue.js 3 and Laravel 9. In this project, there are two database tables - Employee and Company. The company table consists of only an ID and the company name. On the other hand, the Employee table inc ...

Guide to positioning a THREE.js plane onto the exterior of a spherical object

Just starting out with Threejs and 3D graphics. I'm interested in learning how to position a plane of any dimensions on the surface of a sphere. Here's an example image of what I'm aiming for: example image ...

What is the most efficient method for managing axios errors in Laravel and Vue.js?

Currently, I am developing spa web applications using Laravel as the backend and Vue.js as the frontend framework. For authentication with API, I am utilizing Laravel Passport, and for managing my application state, I am using Vuex. Initially, I created A ...

display different vue component based on screen size

I am in search of a method to implement responsive components in Vue.js (Nuxt). I have developed this mix-in but encountering an error: export const mediaQuery = { data() { return { breakpoints: { sm: 576, md: 768, lg: ...

When making jQuery Ajax calls, the $_POST variable may be empty and a warning about headers already being sent may also

I've been working on a PHP project and encountered an issue with sending data from an HTML page using jQuery Ajax to another PHP page. After numerous attempts to debug the problem, I still can't figure out why $_POST is empty when I try to echo. ...

What is the best way to initially conceal content and then reveal it only after an ajax call is made?

Currently, I have a situation where content is revealed after the callback function of a .js library (typed.js) executes. Here is the script I am using: Javascript $(function(){ $("#logo-black").typed({ strings: ["Nothing^450&Co^250.^500" ...

Switching my Selenium code to HtmlUnit: A Step-by-Step Guide

Currently, my Selenium code is working perfectly fine. However, I am looking to convert this code into HtmlUnit. I know I can use the HtmlUnitDriver like WebDriver driver = new HtmlUnitDriver(); I want to make it purely HtmlUnit. Below is the code that I ...

Substitute the attributes of one object with those of another

Alright, I'm revising this because it seems to be causing confusion. Imagine you have two items x and y. What I aim to do is swap all the characteristics of x with those of y. (Please note that this isn't your usual duplication process where a ...

Challenge with Sequelize Many-to-Many Query

Currently, I am facing an issue with connecting to an existing MySQL database using Sequelize in Node. The database consists of a products table, a categories table, and a categories_products table. My goal is to fetch products, where each product includes ...

Issue with Vue js template not correctly binding class properties

Struggling with a code example available at: https://v2.vuejs.org/v2/guide/class-and-style.html Here is a simplified version of my code snippet: var classdata = { "isActive": false } Vue.component('app&a ...

Exploring the power of Typescript functions within a traditional VueJS project

TL;DR: How can I import and use a typescript module into my plain js Vue-Components? I have a Vue 2 (not yet 3) project. In this specific project, I have made the decision to refactor some of the code logic into ES modules for improved testability and reu ...