-1

I've just started using Firebase and i can't get data from database. Here's my code

const books = firebase.database().ref('Books');
var index;
books.once("value", function(snapshot) {
   index = snapshot.val().Count
});

console.log(index)

Console log gives undefined. Where's the problem? Thanks.

RavatSinh Sisodiya
  • 1,596
  • 1
  • 20
  • 42
Krystian
  • 11
  • 4

3 Answers3

0

The issue you're running into is that book.once is asynchronious, so what's actually happening in your code is this.

//set reference to books
//set variable index to undefined
//start a call to update index
//log the value of index
//call to update value finishes, index gets set to something

try moving your console.log inside the books.once block, and see that the value gets logged.

TheCog19
  • 1,129
  • 12
  • 26
  • The output is correct, but i need this value to be global. Is there a way to do this? – Krystian Jun 18 '18 at 11:48
  • It depends on how you define global. You could look into async-await, or you could chain a then off of the call, but inevitably you're going to have to wait for the call to complete one way or another – TheCog19 Jun 18 '18 at 12:32
0

Your call is asynchronous and console.log gets executed even though .once() has not finished yet.

Do this:

books.once("value", function(snapshot) {
  index = snapshot.key; // Count doesn't exist, the index is called "key" in firebase
  return snapshot.val();
}).then(function(books) {
  // This basically makes sure that the .once() callback has been done. Now you can see what's in `books`.
  console.log(books);
});

Edit: You can't access the .val() of books outside of an asynchronous operation. Take a look here for more about async operations.

Fortuna
  • 611
  • 6
  • 18
0

Do this:

const books = firebase.database().ref('Books');
var index;
books.once("value", function(snapshot) {
  index = snapshot.val().Count
}).then(function() {
  console.log(index)
});

What's happening is that the data is temporary and if you try to read 'index' from outside the Firebase function, 'index' would be empty and it would return null, resulting in 'undefined' so you need to put the 'console.log' function either in the 'then(func())' function or with the variable set function in the 'once(action, func())' function.

Maytha8
  • 846
  • 1
  • 8
  • 26
Raj Jaril
  • 376
  • 1
  • 16