M Code
M Code

Reputation: 79

firebase returns undefined user id at one place and the correct value at other

I have the following function to get the user id:

currentUser.js

import firebase from './firebase';

export default function getCurrentUserID() {
  var user = firebase.auth().currentUser;
  var uid; 
  if (user != null) {
    uid = user.uid;  // The user's ID, unique to the Firebase project. Do NOT use
    // this value to authenticate with your backend server, if
    // you have one. Use User.getToken() instead.
    return uid;
  }
  return uid;
}

The following code to enable adding projects using the button, works fine:

addProject.js

import getCurrentUserID from './currentUserID';
import getFirestoreDB from './firestoreDB';
import Project from './project';
const addProjectBtn = document.getElementById('addProjectBtn');
function addProject() {
    const title = prompt('Insert title');
    const description = prompt('Insert Description');
    const project = new Project(title, description);
    const db = getFirestoreDB();
    const currentUserUID = getCurrentUserID();
    alert(currentUserUID); 
    db.doc(`users/${currentUserUID}/projects/${title}`).set({ ...project }).then(() => {
        alert("Success");
    }).catch((error) => {
        alert("Error " + error);
    });
}

export default function enableAddProjectBtnFunctionality() {
    addProjectBtn.addEventListener('click', addProject);
}

But, the following code to display projects, doesn't work. The alert(uid) shows undefined here but shows the correct user id above.

displayProjects.js

import getCurrentUserID from "./currentUserID";
import getFirestoreDB from './firestoreDB';

var db = getFirestoreDB(); 

export default function displayProjects(){
    var uid = getCurrentUserID(); 
    if(uid){
        alert(uid); 
        var projectsRef = db.collection("users").doc(`${uid}`).collection("projects"); 
        projectsRef.get().then((querySnapshot) => {           
                querySnapshot.forEach((doc) => {
                    // doc.data() is never undefined for query doc snapshots
                    console.log(doc.id, " => ", doc.data());
                });
            });  
    }
          
}

Could someone help me figure out what's the problem here and how I could fix it?

Upvotes: 3

Views: 689

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598901

Most likely the displayProjects method is executed before the user sign-in has been completed.

The proper way to pick up the user state in such scenarios is to use an auth state listener as shown in the first code fragment in the documentation on getting the current user.

In your code that'd look like this:

export default function displayProjects(){
  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      var uid = user.uid;
      var projectsRef = db.collection("users").doc(`${uid}`).collection("projects"); 
      projectsRef.get().then((querySnapshot) => {           
        querySnapshot.forEach((doc) => {
          console.log(doc.id, " => ", doc.data());
        });
      });  
    }
  });
}

Upvotes: 1

Related Questions