Julio Quintana
Julio Quintana

Reputation: 1

When my child_removed event is triggered, it also triggers my child_added. How can I avoid this?

Now I'm programming a webapp, with Firebase as a data store.

My question is about that. I set a query for child_added and child_removed perfect, my child_removed is triggered OK, when deleting a child, but when I delete a child, it also triggers my child_added. This is my code:

          db.ref('posts/').limitToLast(1).on('child_added',(snapshot,prevChildKey)=>{

            if(this.newPubsSearch){
                console.log(prevChildKey)
                this.newPubs= true
                console.log(snapshot)
                var pub = snapshot.val()
                pub['.key'] = snapshot.key

                this.pubstmp.unshift(pub)
            }
            this.newPubsSearch = true
        })

        db.ref('posts/').on('child_removed', function(snapshot){
            for(var pub in vm.pubs){
                if(vm.pubs[pub]['.key']==snapshot.key){
                    vm.pubs.splice(pub,1)
                    break
                }
            }
        })

Did it happen to someone else? Thanks for all your help.

Upvotes: 0

Views: 218

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

From how much i understand you code, You are getting a child_added event along with the child_removed event.

But this happens only when the last item is removed from the posts.

According to your code:

db.ref('posts/').limitToLast(1).on('child_added',(snapshot,prevChildKey)=>{...});

child_added will be triggered everytime new child gets added at the end of the posts i.e. the last child (because of limitToLast(1) ). So, whenever the last child of posts is removed, second last child becomes the last child, and firebase takes that as an addition of new child at the last. thus it triggers the child_added event.

For more information, please go through Firebase limitToLast Documentation , and read it throughly and carefully.

Upvotes: 1

Related Questions