Read from real time database not working Firebase

I’m trying to display my username from my Realtime Database but I get this error in my console:

TypeError: Cannot read properties of null (reading ‘studioName’)
at studiodash.js:24:71

I’m not really sure what the issue is. I made sure that my info matched up to what I have in my database. I’d really appreciate it if someone could help me solve this problem. I have provided a screenshot of my database setup and my code. Thanks!

FB Database:

enter image description here

JS:


// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Initialize variables
const auth = firebase.auth();
const database = firebase.database();

//Check if user is signed in and their display info
firebase.auth().onAuthStateChanged( function(user) {
  if (user) {
    database.ref('/studiopick/studio/users/' + user.uid).get().then(snapshot =>{
      document.getElementById
      ("studioName").innerText = snapshot.val().studioName;
      ("profile-name").innerText = snapshot.val().studioName;


    }).catch(e => {console.log(e)})
  } else {
    window.location.href ="login.html?error";
    alert("No active user please sign or sign up.");
  }
}); 



HTML

<!---Edit Profile--->
      <div class="edit-profile" id="edit-profile">
        <div class="card-body">
          <form id="studioForm">
            <h5 class="card-title text-muted"><strong>Edit Profile</strong></h5>
            <p class="profile-title" id="studioName"><b>Enter Studio Name</b></p>
            <p class="profile-location" id="profile-location">Bethesda, MD</p>
            <img class="star" src="Images/Star.png">
            <p class="profile-rating" id="profile-rating">4.25</p>
            <p class="profile-reviews" id="profile-reviews">8 reviews</p>
            
            <img class="card-img-bottom" id="profile-image" src="Images/placeholder.png">

            <button type="button" id="editprofilebutton" onclick="window.location.href='editprofile.html'">Edit Profile</button>
          </form>
        </div>
      </div>
      <!---Edit Profile--->


>Solution :

The val() method of DataSnapshot returns null if that node does not exists. In your case you are trying to read ref('/studiopick/studio/users/' + user.uid) where user.uid is Firebase Auth’s UID and not some username (unless you are setting custom UID using Firebase Admin SDK).

firebase.auth().onAuthStateChanged(async (user) => {
  if (user) {
    const snapshot = await database.ref('/studiopick/studio/users/' + user.uid).get()

    if (snapshot.exists()) {
      document.getElementById("studioName").innerText = snapshot.val().studioName;
    } else {
      console.log("User logged in but user's node not found in DB")
    }
  } else {
    window.location.href = "login.html?error";
    alert("No active user please sign or sign up.");
  }
});

Leave a Reply