Reputation: 2538
I have a list of post
's and I'm fetching them with .on('child_added')
the problem is that I only want to get the post
's when an item is added and not when it is removed, however, it seems that .on('child_added')
gets called even when a post is removed. Which is not what I need in my case.
Here is my function:
if(fromClick) { this.subscription.off(); this.firstRun = true;}
this.postFeed = new Array();
this.subscription = this.database.database.ref('/posts/'+this.locationId)
.orderByChild('created')
.limitToLast(10);
this.subscription.on('child_added', (snapshot) => {
this.postFeed.push(snapshot.val());
});
So it displays last 10
and then when an item is added it adds that to the array as well, but when an item is removed it gets called again..
How can I prevent this? So that the call only happens for post
's that are added?
Upvotes: 1
Views: 276
Reputation: 599716
If you're calling:
this.database.database.ref('/posts/'+this.locationId)
.orderByChild('created')
.limitToLast(10);
You are creating a query that contains the 10 most recent posts. If you remove one of those, another one becomes the 10th most recent posts, so you get a child_added
for that.
The only thing I can imagine is only getting the 10 once, and then doing a limitToLast(1)
:
this.database.database.ref('/posts/'+this.locationId)
.orderByChild('created')
.limitToLast(10)
.once("value", function(snapshot) {
snapshot.forEach(function(child) {
// These are the initial 10 children
});
});
this.database.database.ref('/posts/'+this.locationId)
.orderByChild('created')
.limitToLast(1)
.on("child_added", function(snapshot) {
// This is the latest child, but this will also fire when you remove the current latest
});
Upvotes: 1