Search code examples
javascriptfirebasegoogle-cloud-firestorebrowser-cache

Firestore documents apparently not cached


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?

Edit

Thanks to Mark's answer I have adjusted my initialization of firestore as follows: export const firestore = initializeFirestore(app, {localCache: persistentLocalCache({})});. Now the documents are retrieved from the cache. However, the documents are also retrieved from the server - even twice. I am getting the following output:

Docs from Cache: 8 Docs from Cache: 8 Docs from DB: 8 Docs from DB: 8

The goal would be to see:

Docs from Cache: 8 Docs from DB: 0

What do I have to change to get this result?

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;
};

Solution

  • As per the documentation:

    For the web, offline persistence is disabled by default. To enable persistence, call the enablePersistence method.

    Therefore, the firestore cache is cleared on page refresh and is not persisted, because by default it is uses the memoryLocalCache. To enable persistence, please check the documentation.