0

I am using react native with Firebase Realtime Database. Testing a simple chat app and I am fetching the chats like so:

 this.friendChatRef = this.db.ref('messages/' + this.chat_id + '/' + this.friend_id)

 const friendChatRef = this.friendChatRef.limitToLast(9)

 const fcrp = friendChatRef.once('value')

The goal is to always get the last 9 messages from the conversation when the component/view mounts.

The problem is that It will fetch 9 chats but they are not the latest in any way. I can add 10+ new messages but they will never be fetched until I add this:

 friendChatRef.keepSynced(true)

Then every time I access the chat it will fetch the latest 9 messages.

Why do we have to use keepSynched? I thought persistence is just for the offline data caching but it always checks if the cached data is outdated or not every time you create a ref and fetch the data?

Is there any way to keep the persistence and not use keepSynched to get the latest data?

AlwaysConfused
  • 729
  • 2
  • 12
  • 37
  • "The problem is that It will fetch 9 chats but they are not the latest in any way." The code you shared doesn't read any data yet. If you have a problem, always show the minimal code that reproduces the problem. – Frank van Puffelen Jun 17 '19 at 18:42
  • @FrankvanPuffelen I added extra code, but this is the db ref to get the latest 9 messages from that ref. The key is that without having `keepSynced` simply not going to fetch them as they should and having it to `true`, works as expected – AlwaysConfused Jun 17 '19 at 22:08
  • 1
    You're using `once()`, which doesn't work well together with disk persistence. See my detailed answers here https://stackoverflow.com/questions/40190234/firebase-what-is-the-difference-between-setpersistenceenabled-and-keepsynced/40193807#40193807 and https://stackoverflow.com/questions/34486417/firebase-offline-capabilities-and-addlistenerforsinglevalueevent/34487195#34487195. Essentially: you'll either have to use `on()` or `keepSynced` (which essentially keeps an empty `on()` listener on the location) for this to work.. – Frank van Puffelen Jun 17 '19 at 23:12
  • Its a shame I can not fetch from the cache and then check the db ref once for the new data and have to use `keepSynced` instead as for me to have a listener always is not a good option here – AlwaysConfused Jun 18 '19 at 10:00
  • Calling `keepSynced(true)` adds an empty listener to the location. – Frank van Puffelen Jun 18 '19 at 13:14

0 Answers0