Emanuel Tesař
Emanuel Tesař

Reputation: 11

How to use firebase onSnapshot and maintain consistency

I am developing a React/redux application and my idea is to subscribe to all of my firebase collections using onSnapshot and update the state on each update and React will update the UI on each state change.

However, I have also redux actions which trigger updates in multiple collections (say A and B) and they will result in different onSnapshot calls. This makes my UI inconsistent.

What is the best practice for this in firebase?

Upvotes: 1

Views: 881

Answers (1)

Christina Holland
Christina Holland

Reputation: 211

I'm not totally sure if I'm understanding your case right but I think you're saying that you might do an update that changes 2 collections (A and B) and you have 2 onSnapshot listeners, one on collection A and one on collection B, and these onSnapshot events will not fire at the same time, causing your UI to be out of sync.

So, sort of good news, we are working on a new method called onSnapshotsInSync that I think should only fire once when both listeners are in sync. It's not ready yet but hopefully will be soon. WIP commit here

In the meantime, I'm not sure what the most popular workarounds are but it would involve some kind of client side check of whether your data is in sync. Maybe there is a logical way to check that based on the type of data you have, and if there isn't, one thing I guess you could do is send up the same unique string (timestamp based?) with each of the simultaneous updates, and then have your render code not render if all the data doesn't have the same matching string. This does seem pretty suboptimal so hopefully we can get the new method out soon.

Upvotes: 1

Related Questions