Problem when wanting to use a value obtained from Firebase in Javascript

0

What happens is that the value I get without problems, but wanting to use it outside the code where I get the value, it disappears and does not show any data ...

This is the code where I collect the value "snapshot1" and I contain it in the variable "country", but when wanting to use the variable "country" outside that code, the value of "snapshot1" disappears.

firebase.database().ref().child("users empresas").child(useruid).child("País").on("value", function(snapshot1) {
      var pais = snapshot1.val();
    //console.log("El país del usuario es " + snapshot1.val());
    });

Does anyone know how to use that value of snaptshot1 everywhere without problems?

I hope you can help me, thank you very much!

    
asked by Matías Nicolás Núñez Rivas 11.06.2018 в 00:17
source

1 answer

1

The problem is that by declaring the variable pais within the function, it can only be used in that scope. If you want to use it outside, you must declare it outside of it and assign it the value inside.

For example:

var pais=""; //aquí la variable existe fuera del ámbito de la función
firebase.database().ref().child("users empresas").child(useruid).child("País").on("value", function(snapshot1) {
      pais = snapshot1.val(); //Aquí asignas un valor a la variable
    });

//Aquí puedes usar la variable, y tendrá el valor asignado dentro de la función
console.log("El país del usuario es " + pais);
    
answered by 11.06.2018 / 20:10
source