admin管理员组

文章数量:1323225

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.

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.

Share Improve this question edited Jun 11, 2018 at 13:55 Frank van Puffelen 600k85 gold badges889 silver badges859 bronze badges asked Jun 11, 2018 at 9:19 Sachin NaikSachin Naik 3552 silver badges15 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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.

本文标签: javascriptCache first implementation for get in firestoreStack Overflow