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
You listed quite a few good options. We use pagination in our app to limit the read queries and also to improve the load speed. For example, we only show 50 items per page and load more on click or scroll (infinite scroll) If the data doesn't change often, you can cache it on the frontend, but this introduces a whole lot of additional problems :).
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
})