user14120290
user14120290

Reputation:

Displaying data from Firebase Database into an html document

I'm trying to display data from Firebase Database into an html document. Under you can see both my HTML and JavaScript file. I'm pretty new to Firebase, so I have most likely done a mistake. Appreciating all answers!

Thanks in advance!

HTML:

<p id="profile"></p>

<table id="profiledetails-table">
    <tr id="tr">
        <th>Name</th>
        <th>Email</th>
    </tr>
</table>

Javascript:

firebase.auth().onAuthStateChanged(function(user) {
    var docRef = db.collection('users').doc(firebase.auth().currentUser.uid)

    docRef.get().then(function(snapshot) {
        if (doc.exists) {
            console.log("Document data:", doc.data());

            $('#profiledetails-table').append(doc.data);

        } else {
            console.log("No such document!");
        }
    }).catch(function(error) {
      console.log("Error getting document:", error);
    })
});

Upvotes: 3

Views: 350

Answers (2)

p2hari
p2hari

Reputation: 558

As @Camille mentioned, you need to use snapshot.exists and snapshot.data().

Upvotes: 1

AmiralBl3ndic
AmiralBl3ndic

Reputation: 416

You're trying to use an undefined variable (and your editor/IDE should have warned you): you're using if (doc.exists) but doc is not defined, hence doc.exists will always be undefined or you must have some "Cannot read property exists of undefined" kind of error in your devtools.

This is the way you might want to do it:

firebase.auth().onAuthStateChanged(function(user) {
    var docRef = db.collection('users').doc(firebase.auth().currentUser.uid)

    docRef.get().then(function({ doc }) {
        if (doc.exists) {
            console.log("Document data:", doc.data());

            $('#profiledetails-table').append(doc.data);

        } else {
            console.log("No such document!");
        }
    }).catch(function(error) {
      console.log("Error getting document:", error);
    })
});

I don't really know jQuery so I can't be sure there is no bug in the way you append data to your table, so you might want to have a look at it if this does not work.

Upvotes: 1

Related Questions