When placing a realtime database listener :
firebaseDb.ref(ref).on('value', (snapshot) => {
console.log('snap', snap);
const response = snapshot.val();
});
The snapshot is being cached for a later offline use. If I now refresh the page, my console.log is going to appear twice on my console. The first one will be the cached snapshot, the second one will be the server snapshot.
My application is pretty complex and just to give you an example, I have nested data binding as follow:
const userBind = (userRef: string) => firebaseDb.ref(userRef).on('value', (snapshot) => {
console.log('snap', snap);
const user = snapshot.val();
store.commit(SET_USER, user);
getUserFriends(user)
});
const getUserFriends = await (user: User) => {
const userFriends = async getUserFriendsData() // call our backend
store.commit(SET_USER_FRIENDS, userFriends);
};
Now, store.commit(SET_USER, user); is being called twice, as well as getUserFriendsData() which starts to be a performance issue. I think my best option here would be to disable the realtime database caching.
It would be nice to have a similar feature as the Android SDK: FirebaseDatabase.getInstance().setPersistenceEnabled(true);
What do you guys think?
Kind regards, Florian.
Unfortunately the offline behaviour in the Realtime Database is "build" in without much control on how it works. With Firestore you could detect with the metadata if data is comming from the cache or server. Maybe a migration to that database would be a solution.
With the Realtime Database you could disconnect from the server with goOffline and reconnect later to save the data to the server. But that feels like a messy solution. By using this you would only receive data from the cache but also you would not be able to get new data from the server.
You could also optimze your state management to not rerender if it receives the sama data by using shalow comapres of the data you receive and the one stat is already stored.