0

I can't randomly get user from firebase

I'm doing dating app with react native and firebase.

Users can log in with google and set their accounts, but I can't match users.

I can pick 1 user but cant display user's data.

I tried:

  • i tried get all users from firebase realtime database
  • i can pick 1 user and log user's details but cant display in app

And sometimes user.uid returns null even if i logged in.

function getRandomUser() {
  const numberOfUsers = 15;
  const randomIndex = Math.floor(Math.random() * numberOfUsers);
  var ref = firebase.database().ref("/users/");

  ref
    .limitToFirst(1)
    .once("value")
    .then((snapshot) => {
      var randomUser = snapshot.val();      
      console.log(randomUser);
      console.log(randomUser.bio);//this is not even display in console
    });
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

I believe you should change the way you are referencing your database, so it should be var ref = firebase.database().ref("users"); and not var ref = firebase.database().ref("/users/");.

After that, are some changes related to the random number number and to the comparing issues that you need to perform, so values are returned. Please, give it a try using the below code.

    var dbUser = firebase.database(); 
    var refUser = dbUser.ref("<collection>");
    refUser.orderByChild("online").equalTo(1).on("value", function(Data){
    var numberOfUsers = 15;
    var randomIndex = Math.random() * numberOfUsers;
    var userIndex = parseInt(randomIndex, 10); //parse the random number from double to integer
    var currentIndex = 0;
    var BreakException = {};
    try
    {
        Data.forEach(function(snap){
            if(currentIndex==userIndex){
                var randomUser = snap.val();
                //Do something with your random user
                throw BreakException;
            }
            currentIndex++;
        });
    }
    catch(e){
        if(e!== BreakException) throw e;
    }

While this code is untested, it was based in this successful use case here and I believe should help you. Besides that, you can get another way of returning random users, but with indexes now, by checking this similar case here, with a very complete answer from a Product Lead from Firestore.

gso_gabriel
  • 4,199
  • 1
  • 10
  • 22
  • I get RefrenceError: Can't find variable:Data – Tuna Gündüz Sep 14 '20 at 11:09
  • Hi @TunaGündüz you can try removing the `Data`. Otherwise, give it a try with the new code I have updated. Besides that, please, bear in mind that you will need to adapt this code, as it's **untested** and should be used as base for you application. – gso_gabriel Sep 14 '20 at 12:01