0

I'm trying to retrieve data from database and store the value into a variable, but it gives me undefined value which means variable is not storing the data.

  var n1;
  var reff=firebase.database().ref('login-demi/');
  reff.on("child_added", function(data){
    var newnum=data.val();
    n1=newnum.number; //4
    if (n1==4){
      n1=newnum.age;
    }
  });
  console.log(n1);

But if I try to "put console.log(n1)" inside the function under "n1=newnum.age;" then it will display the value, but i want the variable to store the value and display it outside the function can I know how can I do that?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    variables have scope - determined by where (and in some ways how) they are declared - but all variables are unavailable outside of the function they are declared in - so `n1` inside that function definitely can't be accessed outside of that function - then there's the whole asynchrony thing which you haven't taken into consideration – Jaromanda X Sep 25 '22 at 09:13
  • you can fix the problem by removing `var` inside your function: `n1 = newnum.number` – Kokodoko Sep 25 '22 at 09:16
  • @Kokodoko soory i already tried but it's still undefined – Zeeshan Haider Sep 25 '22 at 09:19
  • @JaromandaX so is there any way i can access it outside the function? – Zeeshan Haider Sep 25 '22 at 09:22
  • 1
    It's undefined because you `console.log()` it before firebase has returned the value. – Kokodoko Sep 25 '22 at 09:26
  • 1
    So your problem is that you do not wait for the data to be loaded from firebase. You can fix that by putting `console.log()` inside the `reff.on()` handler too. Asynchronous data (as this is called) is mostly not available right away. The network takes time to send and receive the message. – Kokodoko Sep 25 '22 at 09:27
  • no, you can't change the scope of a variable to suit your whims – Jaromanda X Sep 25 '22 at 09:34
  • oh, wait, you edited the code - yeah, now it's only the asynchrony that you don't understand that is the problem – Jaromanda X Sep 25 '22 at 09:43

1 Answers1

1

I think the problem is that the function "reff.on" is an event function and what happens is that you print the n1 variable before the function is executed.

Therefore, you will only be able to access this data from within the function, Or you will build a specific function to verify that the previous function has been executed before you print the n1.

Notice how they only access the information from within the function in the Firebase documentation : https://firebase.google.com/docs/reference/js/v8/firebase.database.Reference#parameters