Home > database >  Read from real time database not working Firebase
Read from real time database not working Firebase

Time:09-08

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  id="edit-profile">
        <div >
          <form id="studioForm">
            <h5 ><strong>Edit Profile</strong></h5>
            <p  id="studioName"><b>Enter Studio Name</b></p>
            <p  id="profile-location">Bethesda, MD</p>
            <img  src="Images/Star.png">
            <p  id="profile-rating">4.25</p>
            <p  id="profile-reviews">8 reviews</p>
            
            <img  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--->


CodePudding user response:

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.");
  }
});
  • Related