ngBillz
ngBillz

Reputation: 13

Can I update a Firestore document without rendering the changes immediately?

I have a feature that lets users upvote certain content. The content is sorted in order of upvotes. At the moment if a user upvotes some content, which then has more upvotes than the content displayed ahead of it, the order of the content will immediately change (since I'm using real time Firestore database).

Is there a way I can prevent this from occurring? I want the order to stay the same unless the user refreshes the page.

Upvotes: 1

Views: 1435

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

Is there a way I can prevent this from occurring? I want the order to stay the same unless the user refreshes the page.

Yes, you can prevent this in two ways. The first approach would be to stop using Firestore's realtime updates feature and get the data only once. As you can see, this is possbile if you are simply using a get() call.

According to the official documentation regarding CollectionReference's onSnapshot() function:

Attaches a listener for QuerySnapshot events. The listener can be cancelled by calling the function that is returned when onSnapshot is called.

So the second approach would be to continue using realtime updates feature but to remove the listener once is not needed anymore.

Upvotes: 3

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

It sounds like you're using Firestore's realtime mode, which calls your onSnapshot method whenever there is a change in the data. From the documentation:

db.collection("cities").doc("SF")
    .onSnapshot(function(doc) {
        console.log("Current data: ", doc.data());
    });

Cloud Firestore also has a method that simply reads the data once. You can use this to just show the data once, or to retain full control over when the data gets read. From the docs:

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    }
})

Upvotes: 3

Related Questions