A built-in caching solution for firestore #471
adamfarmer0
started this conversation in
Ideas
Replies: 1 comment 3 replies
-
Hi @adamfarmer0, Firestore handles offline caching for you once you enable it. You can check whether data came from the network or cache via |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I found out that with persistence and local caching, I can check the cache timestamp and server timestamp, then update cache if server timestamp is bigger than cache timestamp.
Let's say we have a document full of document Ids and timestamps called "CachedDocuments" as array, that shows when the documents are created and updated, and we are always subscribed to that document,
Let's say that we are trying to get a document by their Id,
We first try to get the document with
const cachedData = getDocFromCache(doc(db, "CollectionName", id));
If it exists and If
cachedData._document.version.timestamp.seconds > CachedDocuments[id].timestamp.seconds;
We return the data from cachedData, else, we send request to server, get the data, and persistence updates the cache automatically.
I am not sure if it's already builtin to the persistence cache, If it is, then it's redundant to write this.
Otherwise, I believe this would enormously reduce read counts to the server, I am wondering if this could be implemented in reactfire itself as a ReactFireOptions when reading a collection or a document, where reactfire handles the reads and writes to some "updates" document that is like
[{ Idkey : timestamp }, { Idkey2 : timestamp} ...]
pairs.Edit:
More detailed explanation:
CacheTimestamp > DocIdUpdateTimestamp ? return CachedData, since Document didn't update from the time Cache was initialized.
CacheTimestamp < DocIdUpdateTimeStamp ? return getNewData(), since Document did update with a new timestamp, so the cache is old.
after getNewData(), Persistence auto updates CacheTimestamp, therefore in the next call, CacheTimestamp will be bigger than DocIdUpdateTimestamp, so the CachedData will return, and getNewData will never run until the next time the document is updated.
Beta Was this translation helpful? Give feedback.
All reactions