Lucas Gaspar
Lucas Gaspar

Reputation: 331

Firebase array always return false

I'm creating an application with ionic and firebase. I'm trying to verify if a element exists in my array, and if it does, I need to return true, else I need to return false. The problem is, it always return false, even if the item exists in firebase. Can you please tell me what is going wrong with following code?

Here's my service:

function IsReserved(id){
    var ref = fb.child('/reserved/').orderByChild('product').equalTo(id);
    ref.once("value").then(function(snapshot){
        snapshot.forEach(function(data){
            if(data.val().user === $rootScope.currentUser.$id){
                console.log(data.val().user + " * " + $rootScope.currentUser.$id);
                return true;
            }
        });
    });

    return false;
}

Here is my controller:

function Reservar(produto) {
if(!$rootScope.cart){
  $rootScope.cart = [];
  $rootScope.fprice = 0;
}

var user=$rootScope.currentUser;
var res = vm.IsReserved(produto.$id);
console.log(res);


if(res){
    console.log("já reservado");                
    return;
}

Here is my firebase strucure:

-reserved:
     --KdS2cH1OJ5MhKAV6Yio:
            -product: "product1"
            -user: "W30BB1RMg1XhNo9og9cMo4Gpr4S2"

Upvotes: 0

Views: 209

Answers (1)

Alexandre Justino
Alexandre Justino

Reputation: 1726

Your code won't work because firebase works asynchronously.

You should use a callback function as a parameter, something like this:

function IsReserved(id, callback){
            var ref = fb.child('/reserved/').orderByChild('product').equalTo(id);
            ref.once("value").then(function(snapshot){
                snapshot.forEach(function(data){
                    if(data.val().user === $rootScope.currentUser.$id){
                        console.log(data.val().user + " * " + $rootScope.currentUser.$id);
                        callback(true);
                        return;
                    }
                });
            });
            
            return false; //-- This will always be executed before the code inside the .then, that's why your function always returns false
        }

And on you controller, something like this:

function Reservar(produto)
        {
            if(!$rootScope.cart){
              $rootScope.cart = [];
              $rootScope.fprice = 0;
            }

            var user=$rootScope.currentUser;
            vm.IsReserved(produto.$id, function(response){
               console.log(response);
               if(response){
                console.log("já reservado");                
               }
            });
  }
            

Could you understand?

Upvotes: 2

Related Questions