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

Customize the dynamic options for selecting with Bootstrap

I have been experimenting with the bootstrap select plugin and have run into an issue while trying to dynamically add options using Javascript. Unfortunately, the list always appears empty. Interestingly, when I revert back to using a conventional HTML sel ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Prevent the submit button from being clicked again after processing PHP code and submitting the form (Using AJAX for

I've set up a voting form with submit buttons on a webpage. The form and PHP code work fine, and each time someone clicks the vote button for a specific option, it gets counted by 1. However, the issue is that users can spam the buttons since there i ...

How can Redux help persist input value through re-rendering?

Handling Input Value Persistence in Redux despite Re-rendering? I am currently able to store and save input values, but only the data from one step ago. For example, when I click on the second input field, it displays the value from the first input fiel ...

Restrict dropping items in HTML5 by only allowing the drop if the target div is

I am working on developing a user-friendly visual interface for creating simple graphics. The interface includes 10 image icons and 5 boxes where users can place these icons. Users have the freedom to select which icon they want to display and arrange them ...

Implementing pagination using getServerSideProps in NextJS allows for dynamic

I'm currently using NextJS along with Supabase for my database needs. I'm facing a challenge with implementing pagination as the solution I'm seeking involves passing queries to the API. However, since I'm fetching data directly from th ...

Real-time Data Stream and Navigation Bar Location

Utilizing the EventSource API, I am pulling data from a MySQL database and showcasing it on a website. Everything is running smoothly as planned, but my goal is to exhibit the data in a fixed height div, with the scrollbar constantly positioned at the bott ...

What is the reason behind obtaining a distinct outcome when logging the properties of an object compared to logging the object itself and checking its properties?

Currently, I am working on integrating socket-io with react redux and encountering a peculiar namespace problem. console.log(socket); console.log(socket.disconnected); console.log(socket.id); console.log(socket); The first log displays a comprehensive ob ...

Leverage API request within the component

Experimenting with VueJS, I am attempting to execute an api call from a component: var postView = { props: ['post'], template: '<li>{{ post.title }}</li>', url: 'https://jsonplaceholder.typicode.com/posts&a ...

What is the best way to establish a new JavaScript data type that can be accessed using both key and index?

Looking to create a unique datatype or object in JavaScript that allows access by both index and key, as well as having a length property to display the number of items in the datatype. Something along the lines of: MyDataType[0].name="John" MyDataType[0 ...

Looking to create circular text using HTML, CSS, or JavaScript?

Is there a way to generate curved text in HTML5, CSS3, or JavaScript similar to the image linked above? I've experimented with transform: rotate(45deg); but that just rotates the text without curving it. Additionally, when using Lettering.JS to curve ...

I need to figure out a way to validate form data dynamically as the number of fields constantly changes. My form data is being sent via Ajax

Click validation is desired. It is requested that before transmitting data, the validate function should be executed. If there is an empty field, a message should be displayed and the data should not be sent to the PHP file. In case there are no empty fi ...

Having trouble with your jQuery animation on a div?

Check out this jsFiddle example: http://jsfiddle.net/uM68j/ After clicking on one of the links in the demo, the bar is supposed to smoothly slide to the top. However, instead of animating, it immediately jumps to the top. How can I modify the code to ac ...

I am experiencing issues with datejs not functioning properly on Chrome browser

I encountered an issue while trying to use datejs in Chrome as it doesn't seem to work properly. Is there a workaround for this problem if I still want to utilize this library? If not, can anyone recommend an excellent alternative date library that ...

How to Handle Jquery POST Data in Express Servers

Update Make sure to check out the approved solution provided below. I ended up fixing the issue by removing the line contentType: 'appliction/json', from my POST request. I'm facing a problem trying to send a string to Node.js/Express becau ...

Mastering React hooks: A guide to effectively updating and rendering elements

Each time I click the delete button, it seems to only remove the last element instead of the specific one based on index. Is there a better way to achieve this without changing from <input defaultValue={name} /> to <input value={name} /> in t ...

Validating forms in express.js

I need to validate a form that includes user details. In addition to the basic validation for checking if fields are not empty, I also want to verify if the username/email exists in the database. For the email field, I need to ensure it is not empty, follo ...

The persistent issue of window.history.pushstate repeatedly pushing the identical value

I need some assistance with my Vue application. I am trying to update the URL when a user clicks on an element: const updateURL = (id: string) => { window.history.pushState({}, '', `email/${id}`); }; The issue I'm facing is th ...

Utilize Haxe Macros to swap out the term "function" with "async function."

When I convert haxe to JavaScript, I need to make its methods asynchronous. Here is the original Haxe code: @:expose class Main implements IAsync { static function main() { trace("test"); } static function testAwait() { ...

What is the functionality of the toArray method?

var retrieveDocs = function (db, callback) { var collection = db.collection('tours'); collection.find({ "tourPackage": "Snowboard Cali" }).toArray(function (err, data) { console.log(data); callback; }) } Is there a p ...