0

While I am assigning value got from the firebase collection it is giving me the below error.

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

Below is my code.

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 it is giving me such kind of error and how can I fix it?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • the problem doesn't seem to be a vue but a js one. check this line `this.email = doc.data().email;`. try console logging `doc.data()`, `doc.data` and `doc`. I have used firebase in a while but it's something with the keys u are trying to access – Kwesi Smart Sep 17 '20 at 14:54
  • `setUsers: () => {}` should be `setUsers() {}` (don't use an arrow function when declaring methods) – tony19 Sep 18 '20 at 04:30

2 Answers2

1

this will lost his scope in firebase callback function.

you have to assign your this object to some variable and then you can use it inside firebase callback.

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);
  });
},
Ahmad Noor
  • 149
  • 8
0

Can you try to console instance.email?

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

It should show an empty string. If its undefined, then that's where the error is coming from.

If its not undefined, then you should check if doc.data().email exists.