Reputation: 37
Let's say I have a Firebase firestore database table called "Articles".
I pull in a list of articles whenever I open the app, and through a FlatList component, whenever I reach the end, I pull in more articles using startAt() and endAt()
I also have the ability to like or comment on articles, so whenever I do so, the current articles in the screen get updated (like counter, comment counter gets updated).
However, I also have a separate backend that adds additional articles to the database after 6 hours interval.
If I subscribe to changes in the Articles database, the startAt() and endAt() will get messed up if new data is added when the user is scrolling through the Flatlist (right?). Instead, I only want to notify the user whenever new articles are added, and display a "New Posts Available" button at the top whenever there are any, and if user clicks on it, it just refreshes the list.
However, I still want to listen to changes in likes and comments of the article, without adding any new articles to the flatlist when the backend adds them.
How do I go about solving this?
Upvotes: 2
Views: 1679
Reputation: 50930
You can check for the type of event i.e. if the document was created
, modified
or deleted
as mentioned in documentation. In case a new document is added, the type will be "created"
. Then just don't append them to your Flatlist. Any updated to likes count will be a "modified"
event so you can just update that in the list. Here's an example copied from the docs:
db.collection("cities").where("state", "==", "CA")
.onSnapshot((snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === "added") {
console.log("New city: ", change.doc.data());
}
if (change.type === "modified") {
console.log("Modified city: ", change.doc.data());
}
if (change.type === "removed") {
console.log("Removed city: ", change.doc.data());
}
});
});
Important: The first query snapshot contains added events for all existing documents that match the query. This is because you're getting a set of changes that bring your query snapshot current with the initial state of the query. This allows you, for instance, to directly populate your UI from the changes you receive in the first query snapshot, without needing to add special logic for handling the initial state.
So the first time the user opens you app and at the same time the new documents were being added, they may end up in the list. If you still want to be strict with the time these docs were added, you can try adding a condition which says documents returned in the query should be created before a particular timestamp.
.where("addedAt", "<=", <the-timestamp>)
Upvotes: 1