Home > Back-end >  Undefined while retrieving current user data from firestore/firebase
Undefined while retrieving current user data from firestore/firebase

Time:09-28

If I print current logged in user

 console.log(firebase.auth().currentUser.uid)

Then it prints the user UID.
Then I tried to fetch current user information from firestore doing

  import firebase from 'firebase/app'
  import "firebase/auth"
  import db from '../firebase/firebaseInit'

  async getCurrentUser(){
    const database = 
    db.collection('users').doc(firebase.auth().currentUser.uid)
    const dbResults = await database.get()
    console.log(dbResults.data())
}

Then it prints undefined

CodePudding user response:

db.collection("users").where("userId", "==","pass the id you have")
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
           
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch((error) => {
        console.log("Error getting documents: ", error);
    });

CodePudding user response:

  1. Did you set up a user collection in your firestore to store the users? Was the user uid stored in it? Firestore does not do this automatically so if you have not set one up then of course you get no results.

  2. Was your db set up properly? Were you able to connect to your db with other methods using current db function?

Also for best practice, its a good idea to rename your database to docRef and dbResult to docSnap instead since it is a reference to a document!

  • Related