I want firestore to fetch data first from cache every time. As per Firestore documentation passing "cache" or "server" options must enable the same. Example below
db.collection("cities").where("capital", "==", true)
.get("cache")
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
However whether i set "cache" or "server", query seems to try network first followed by cache.
Reading data from Firestore There are two ways for retrieving data, which is stored in Cloud Firestore. Calling a method to get the data. Setting a listener for receiving data changes events. We send an initial snapshot of the data, and then another snapshot is sent when the document changes.
Cloud Firestore supports offline data persistence. This feature caches a copy of the Cloud Firestore data that your app is actively using, so your app can access the data when the device is offline. You can write, read, listen to, and query the cached data.
Firebase Hosting uses a powerful global CDN to make your site as fast as possible. Any requested static content is automatically cached on the CDN. If you redeploy your site's content, Firebase Hosting automatically clears all your cached static content across the CDN until the next request.
We use the data parameter to get docPath , the value of the Firestore document path (slash-separated). This value is passed from the client calling the Cloud Function (see below). We then call the asynchronous listCollections() method on the DocumentReference created by using docPath (i.e. admin. firestore().
Since a get()
only gets your a value once, it will always check for the latest value for the data from the server. If this is the first Firestore operation in your app, this may require that it establishes the network connection to the database, which may take some time.
If you quickly want to get the data from the cache, and then later get the modifications from the server, use onSnapshot
:
db.collection("cities").where("capital", "==", true)
.onSnapshot(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
Also see the Firestore documentation on getting realtime updates
To tell get()
to return data from the cache, do:
db.collection("cities").where("capital", "==", true)
.get({ source: 'cache' })
.then(function(querySnapshot) {
...
But note that this means you will never get the updated value from the server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With