0

I want my object property to return the number of children of each section:

function getFB (category){
        var num;
        firebase.database().ref(category).once('value', (snapshot) => {
            num = snapshot.numChildren()
            return (num);
            console.log(num);
        })
  }
 const menu = [
    { // to json/firebase
        title: 'category1',
        subtitle: getFB('category1'),
    },
    { // to json/firebase
        title: 'category2',
        subtitle: getFB('category1'),
    },
  ]

It does give me the number in the console log, but is not printing it back as the value of "subtitle".

What can I do?

  • You're not returning anything from the top-level code in `getFB`. More importantly though: loading data from Firebase happens asynchronously, and any code that needs the data from Firebase needs to be inside the callback, or be called from there. For a longer explanation and examples, see https://stackoverflow.com/questions/40688268/why-does-firebase-lose-reference-outside-the-once-function/40688890#40688890 – Frank van Puffelen Jun 09 '21 at 14:49
  • Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – zero298 Jun 09 '21 at 15:18

0 Answers0