I am trying to reduce the reads from Firestore by adding timestamps to my documents and first getting them from the cache and then only those from the database with a newer timestamp.
When I run this code, however, the documents are always retrieved from the database. The cache remains empty even though – from my understanding – the cache snapshot should have the previously retrieved documents, right?
What am I doing wrong? Why are the documents not being cached?
export const getDocs = async (query) => {
const docsData = [];
var snapshotDb = null;
try {
const snapshotCache = await getDocsFromCache(query);
if (!snapshotCache.empty) {
const latestTimestamp = getLatestTimestamp(snapshotCache.docs);
snapshotCache.docs.forEach(doc => docsData.push({ id: doc.id, ...doc.data() }));
console.log('Docs from Cache: ', snapshotCache.docs.length);
snapshotDb = await getDocsFromServer(query, where('timestamp', ">", latestTimestamp));
console.log('Docs from DB: ', snapshotDb.docs.length);
snapshotDb.docs.forEach(doc => {
if (!docsData.some(d => d.id === doc.id)) {
docsData.push({ id: doc.id, ...doc.data() });
}
});
} else {
snapshotDb = await getDocsFromServer(query);
console.log('Docs from DB: ', snapshotDb.docs.length);
snapshotDb.docs.forEach(doc => docsData.push({ id: doc.id, ...doc.data() }));
}
} catch (error) {
console.error(error);
}
return docsData;
};