James
James

Reputation: 719

Assign value from firebase callback

I want to access my firebase DB, retrieve a value and then assign it to a variable to be used later in the code.

<script src="https://www.gstatic.com/firebasejs/5.5.0/firebase.js"></script>

var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };

firebase.initializeApp(config);
database=firebase.database();
var ref = database.ref('test');
var firebaseMsg ='';

ref.on('value',function(snap){
//console.log(snap.val());
firebaseMsg=snap.val();
});

console.log(firebaseMsg);

my firebase database looks like this:

    {
  "test" : "Hello from my database!"
}

the console log produces an empty string, it seems that the assignment in the ref.on callback doesn't work.

Upvotes: 0

Views: 301

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

This happens because queries to the Firebase database are asynchronous: your console.log() executes before the callback function returned by the on() method is returned.

The following will work:

ref.on('value',function(snap){
   //console.log(snap.val());
   firebaseMsg=snap.val();
   console.log(firebaseMsg);
});

as you have probably noticed since there is a console.log(snap.val()); line that you commented out.

This means that, for example, you can only update your application UI (to reflect a change in the database) from within the callback function.

Upvotes: 1

Related Questions