imconnor
imconnor

Reputation: 415

Firebase user ID variable to retrieve data

Using Firebase, I am trying to display a user's profile information based on their user id. I can currently save data to the database under the users ID.

enter image description here

I am able to display the general information from hobbies, but when altering the variables to display the user's data the id is then null or uid undefined and i can't figure out why? The user is signed in, and can upload data using their id.

//Display Profile Information
(function(){                

var user = firebase.auth().currentUser;
var uid;

if (user != null) {
uid = user.uid;  
}


const preObject = document.getElementById('object');
const list = document.getElementById('list');

//Displays Hobbies correctly, When changing 'object' & 'hobbies'
//to 'Users' & uid nothing is shown. 
const dbRefObject = firebase.database().ref().child('object');
const dbRefList = dbRefObject.child('hobbies');

dbRefObject.on('value', snap=> {
    preObject.innerText = JSON.stringify(snap.val(), null, 3);
});

dbRefList.on('child_added', snap => console.log(snap.val()));

};

Alterations:

const dbRefObject = firebase.database().ref().child('Users');
const dbRefList = dbRefObject.child(uid);

I am extremely grateful for any help or advice!

Upvotes: 0

Views: 1347

Answers (1)

Jim Lowell
Jim Lowell

Reputation: 328

It looks like you are getting a value for dbRefObject which is pointed to the entire Users object and not a specific user's UID.

Try changing this:

dbRefObject.on('value', snap=> {
    preObject.innerText = JSON.stringify(snap.val(), null, 3);
});

to this (dbRefObject changes to dbRefList):

dbRefList.on('value', snap=> {
    preObject.innerText = JSON.stringify(snap.val(), null, 3);
});

Upvotes: 1

Related Questions