1

I've recently gotten started with Firebase development in React.js -

At the moment, I'm trying to pull from the database and create a new object with the data.

This is the code:

var arr = firebase.database().ref("news");//this is the ref.

arr.once('value', function (snapshot) {//will return the array value
    model = {//this is the model i want to .push()
        title: title,
        content: content,
        img: img,
        category: category,
        likes: likes,
        id: snapshot.val().length//This is where I want to add the arr.length
    };

    var promise = arr.push(model);

    promise.then(function(){
        ...
    })
})

The problem is that arr.push(model) runs BEFORE the model.id variable is loaded.

6
  • Does the snapshot argument has a val() function? Commented Mar 27, 2018 at 13:24
  • snapshot.val() get you a javascript object. do you want to get how many children in it? Commented Mar 27, 2018 at 13:32
  • @Luis I’ve tried that but it wont work either! Maybe calling an ‘on’ function when the array.val() is called? Don’t know how to implement it.. Commented Mar 27, 2018 at 13:32
  • The array.push is called before the snapshot.val()... .val() is asymchronous :( Commented Mar 27, 2018 at 13:38
  • 1
    can you show the full code? Commented Mar 27, 2018 at 13:48

2 Answers 2

1

What happens here is snapshot.val() returns a object and not a array. Hence, it would return undefined if u try to access snapshot.val().length.

Now the solution is to convert object to array to get the count.

id: Object.keys(snapshot.val()).length

This might solve your problem.

Sorry if this is not what you are looking for.

Sign up to request clarification or add additional context in comments.

1 Comment

@Hareesh, that would be a better solution.
0

@Meghashyam solution should work. Firebase also have a utility snapshot.numChildren(); which will return number of child properties of this DataSnapshot, if object is empty it will return 0

model = {
    title: title,
    content: content,
    img: img,
    category: category,
    likes: likes,
    id: snapshot.numChildren()
};

You can check more details here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.