Search code examples
javascriptfirebasefirebase-realtime-databasestring-concatenation

Referencing firebase database with a variable and string concatenation


As you can see below i'm trying to read a list of data from the database and then loop over the result, in javascript. The function runs whenever i open/refresh the page:

firebase.database().ref("Users/" + uid + "/rooms").on("value", function(snapshot) {

    snapshot.forEach(function(e) {

         var element = e.val();

         var roomId = element.Id;

    });
});

However, that string concatenation to specify the User Id doesn't work for some reason. When i replace it with the user Id directly like this:

firebase.database().ref("Users/GR3JFsMrKOjCrLhDNFMaq72COd07/rooms").on.....

that works fine. But of course i want to use the variable which contains the Id of the current user.

The uid variable is assigned a value in the onAuthStateChanged when checking if the user is signed in:

firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.

uid = user.uid;

If I add a console.log like this:

firebase.database().ref("Users/" + uid + "/rooms").on("value", function(snapshot) {

console.log(snapshot.parent);

    snapshot.forEach(function(e) {

the output with the first code example (using uid variable) is: undefined. If i specify the User Id directly it is: room-id-1 (the result i want).

How do i make the string concatenation work? Or is this the wrong way of specifying the path of the current user?


Solution

  • It is extremely unlikely that the problem is in the string concatenation itself. It is much more likely that uid simple doesn't have a value yet when you start reading from the database.

    To make sure the uid is available, put the reading of the data into the auth state listener like this:

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        uid = user.uid;
        console.log("uid="+uid);
        firebase.database().ref("Users/" + uid + "/rooms").on("value", function(snapshot) {
          snapshot.forEach(function(e) {
            var element = e.val();
            var roomId = element.Id;
            console.log("roodId="+roomId);
          });
        });
      }
    })