Ben Cavenagh
Ben Cavenagh

Reputation: 748

Fetching UID from Firebase from username

I am trying to create a friends list of sorts from Firebase but can't figure out where I am going wrong. I have this function to fetch a user based on an username input:

handleAddMember = () => {
    var username = prompt("Enter the person's username and press submit");
    if (username != null) {    
        this.findUsersMatchingUsername(username);
    }
}

findUsersMatchingUsername( username ) {
    let userRef = fire.database().ref('users');
    userRef.orderByChild('username').equalTo(username).once('value', snap => {
        if(snap.val()){
            console.log(snap.val());
        }else{
            alert(username + ' exists?: false');
        }
    });
}

It works as expected and it returns this when there is an username in the database (snap.val()) : enter image description here

Here is the data structure: enter image description here

How come when I try to console.log(snap.val().id) it just returns undefined? The id is right there in the snapshot. Also snap.key return 'users' so I'm guessing that I need to go one level further into the database but how do I do that if the next level is just a bunch of uids and I can't seem to get the uid?

Upvotes: 1

Views: 95

Answers (1)

JeremyW
JeremyW

Reputation: 5272

Since you are performing a query, you'll always get a set of results back, even if it's only one result. If you're only intending to pull in ONE user, then I recommend you include the username as part of the reference:

findUsersMatchingUsername( username ) {
    fire.database().ref(`users/${username}`).once('value', snap => {
        if(snap.val()){
            console.log(snap.val());
        }else{
            alert(username + ' exists?: false');
        }
    });
}

On the other hand, if you intend to get multiple users back, then to access each one's properties then you need to go one level deeper, just like you suspected... and to do that I would loop over them, something like:

findUsersMatchingUsername( username ) {
    let userRef = fire.database().ref('users');
    userRef.orderByChild('username').equalTo(username).once('value', snap => {
        let results = snap.val() ? snap.val() : {};
        if (results == {})
        {
            alert(username + ' exists?: false');
            return;
        }
        Object.keys(results).forEach( eachKey => {
            console.log(results[eachKey]);   // Print the whole object in question
            console.log(results[eachKey]['id']);   // Print just the ID of the current object
            // EDIT: Since it's double-nested, you *might* have to do something like:
            // console.log(results[eachKey][eachKey]['id']);   // Print just the ID of the current object
        });
    });
}

Upvotes: 1

Related Questions