Skip to content

Firebase Database console.log() returning Null in Javascript

I hope to seek help from someone if possible. In the following code. Im trying to console.log() data from My Firebase reference as you can see in my code below. But the Console.log() is returning null instead of the values that are there in Firebase Realtime Database. I have also provided the code for adding which is working well. Please have a look the image of my database if it helps. I am not getting any other error in my console except the fact that this is returning null. enter image description here

function addFamilyMember() {
  var NameOfMember = document.getElementById("newFamilyMemberName").value;
  var DoBOfMember = document.getElementById("newFamilyMemberDoB").value;
  var EmailOfMember = document.getElementById("newFamilyMemberEmail").value;
  var ContactOfMember = document.getElementById("newFamilyMemberContactNo").value;

 if (
  NameOfMember.length == "" ||
  DoBOfMember.length == "" ||
  EmailOfMember.length == "" ||
  ContactOfMember.length == ""
) {
   alert("Please enter all details of your Family Member");
} else {
   var user = firebase.auth().currentUser;
   var uid;
   if (user != null) {
     uid = user.uid;
   }

firebase
  .database()
  .ref("/Users/" + uid + "/Family/" + NameOfMember)
  .set({
    MemberName: NameOfMember,
    MemberDOB: DoBOfMember,
    MemberEmail: EmailOfMember,
    MemberContact: ContactOfMember,
  });
 }
}

var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}

firebase
  .database()
  .ref("/Users/" + uid + "/Family/")
  .on("value", function (snap) {
    var mName = snap.child("MemberName").val();
    var mDOB = snap.child("MemberDOB").val();
    var mEmail = snap.child("MemberEmail").val();
    var mContact = snap.child("MemberContact").val();

    console.log(mName + " " + mEmail + " " + mContact + " " + mDOB);
});

Answer

When loading the page for the first time, firebase.auth().currentUser shouldn’t be used because Firebase Auth needs to check if the user’s login session is valid first.

let currentUserFamilyRef = null;

// for use with .on("value") and .off("value")
function onValueFamilyListener(snapshot) {
  const familyMembers = [];
  snapshot.forEach((familyMemberSnapshot) => {
    const MemberName = snap.child("MemberName").val();
    const MemberDOB = snap.child("MemberDOB").val();
    const MemberEmail = snap.child("MemberEmail").val();
    const MemberContact = snap.child("MemberContact").val();
    
    familyMembers.push({ MemberName, MemberDOB, MemberEmail, MemberContact });

    console.log(MemberName + " " + MemberDOB + " " + MemberEmail + " " + MemberContact);
  }

  // TODO: do something with the array of family members familyMembers
}

// for showing loading state
function showLoadingIcon(visible) {
  if (visible) {
    // TODO: show the icon
    // TODO: disable the submit button
  } else {
    // TODO: hide the icon
    // TODO: enable the submit button
  }
}

// for when addFamilyMember() is called while signed out
function addFamilyMemberSignedOut() {
  alert('You need to sign in first!');
  return false;
}

// for when addFamilyMember() is called while signed in
function addFamilyMemberSignedIn() {
  const NameOfMember = document.getElementById("newFamilyMemberName").value;
  const DoBOfMember = document.getElementById("newFamilyMemberDoB").value;
  const EmailOfMember = document.getElementById("newFamilyMemberEmail").value;
  const ContactOfMember = document.getElementById("newFamilyMemberContactNo").value;

  if (
    NameOfMember.length == "" ||
    DoBOfMember.length == "" ||
    EmailOfMember.length == "" ||
    ContactOfMember.length == ""
  ) {
    alert("Please enter all details of your Family Member");
    return false;
  }
  
  const user = firebase.auth().currentUser;
  
  if (user === null) {
    // shouldn't get here, but just in case.
    alert('You need to sign in first!');
    return false;
  }
  
  const uid = user.uid;
  
  showLoadingIcon(true);

  firebase
    .database()
    .ref("/Users/" + uid + "/Family/" + encodeURIComponent(NameOfMember)) // escape names as they may contain symbols, etc.
    .set({
      MemberName: NameOfMember,
      MemberDOB: DoBOfMember,
      MemberEmail: EmailOfMember,
      MemberContact: ContactOfMember,
    })
    .then(
      () => {
        // saved family member's data successfully
        showLoadingIcon(false);
        // reset form
        document.getElementById("newFamilyMemberName").value = "";
        document.getElementById("newFamilyMemberDoB").value = "";
        document.getElementById("newFamilyMemberEmail").value = "";
        document.getElementById("newFamilyMemberContactNo").value = "";
        alert('Information saved!');
      },
      (err) => {
        // failed to save family member's data
        showLoadingIcon(false);
        // err.code may lead to more specific error information
        console.error(err);
        alert('Failed to save information!');
      }
    );
}

// for calling the correct addFamilyMember version
let addFamilyMember = addFamilyMemberSignedOut;

showLoadingIcon(true); // while loading the user's info, show a loading icon

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // A user is (newly/already) signed in.
    // create a reference for this user's family
    const newUserFamilyRef = firebase.database()
      .ref("/Users/" + user.uid + "/Family");
    if (currentUserFamilyRef !== null) {
      // if the old user and new user are the same, do nothing
      // but if they've changed, remove the old listener and update currentUserFamilyRef
      if (!currentUserFamilyRef.isEqual(newUserFamilyRef)) {
        currentUserFamilyRef.off("value", onValueFamilyListener);
        currentUserFamilyRef = newUserFamilyRef;
      }
    } else {
      currentUserFamilyRef = newUserFamilyRef;
    }
    // use the "signed in" version of addFamilyMember
    addFamilyMember = addFamilyMemberSignedIn;
    // attach listener to "/users/{user.uid}/Family"
    currentUserFamilyRef.on("value", onValueFamilyListener);
  } else {
    // no user is signed in.
    // use the "not signed in" version of addFamilyMember
    addFamilyMember = addFamilyMemberSignedOut;
    // if a user was logged in, clean up it's listener to prevent errors
    if (currentUserFamilyRef !== null) {
      currentUserFamilyRef.off("value", onValueFamilyListener);
    }
    // no user, so set the reference to null
    currentUserFamilyRef = null;
  }
  showLoadingIcon(false);
});