How to optimize read-write operations in cloud Firestore?

后端 未结 2 558
长发绾君心
长发绾君心 2021-01-23 11:54

I am currently writing a react + Firebase project for learning purpose, and I am wondering which approach should I take to read from firebase efficiently.

Say I have this

2条回答
  •  面向向阳花
    2021-01-23 13:00

    You should definitely introduce a pagination strategy. Another smart way is to query based on last mutation time. Firestore automatically caches your data in the web if enablePersistence is configured(Otherwise its set to false).

    You might introduce a strategy to only query using the network after a certain period has passed. You need to keep track per module when the last online query was made though.

    function strategicFirestoreReadWrite(moduleKey, actionFn) {
      const lastFetchedDate = sessionStorage.getItem(moduleKey) || new Date();
      const difference = Math.abs(lastFetchedDate.getTime() - new Date().getTime())
      const hourDifference = difference  / 1000 / 3600
      const logToStorageFn = () => {
        sessionStorage.setItem(moduleKey, new Date())
      }
    
      // Performing operation offline when last fetch earlier than 3 hours
      if (hourDifference < 3) {
       firebase
         .firestore()
         .disableNetwork()
         .then(actionFn)
         .then(logToStorageFn)
      } else {
       firebase
           .firestore()
           .enableNetwork()
           .then(actionFn)
           .then(logToStorageFn)
      }
    }
    

    This can be a utility function for all your Firestore operations for a specific page session. Now what you wanna do is pass a unique identifier and whatever offline or online action you want to perform; maybe a fetch, insert, update or delete; with a function. You will be sure that the function performs in either in offline or online mode based on last read-write time.

    strategicFirestoreReadWrite(window.location.href, () => {
    
       //whatever operation you want to perform in online or offline mode
    })
    

提交回复
热议问题