Locally save data using firestore and sync later

1.9k views Asked by At

I am facing an issue integrating the offline behavior of google firestore into my polymer application.

I have created an element to preform all the database operation with firestore. I have initialized the connection in the constructor and below is code.

constructor() {
            super();
            if (!this.db) {
                firebase.firestore().enablePersistence()
                    .then(() => {
                        this.db = firebase.firestore();
                    })
                    .catch((err) => {
                        if (err.code == 'failed-precondition') {
                        } else if (err.code == 'unimplemented') {
                        }
                    });
            }
        }

I have created another function which saves user details to firestore.

saveUserAndSync() {
            this.db.collection("users").add(this.userObj)
                .then(function (docRef) {
                    console.log("Document written with ID: ", docRef.id);
                })
                .catch(function (error) {
                    console.error("Error adding document: ", error);
                });
        }

This works great even if it is offline. The biggest problem that i am facing is if the application is offline and i create user and at the same time if i reload the page all the data is lost and the sync with firestore wont work.

Can anyone suggest a work around for this.

I was able to do the same implementation using pouchDB and couchDB, as pouchDB api will first save the data locally and then sync it with couchDB.

But with firestore it fails.

1

There are 1 answers

2
Doug Stevenson On

For web application, offline storage is not enabled by default. From the documentation:

For the web, offline persistence is disabled by default. To enable persistence, call the enablePersistence method. Cloud Firestore's cache isn't automatically cleared between sessions. Consequently, if your web app handles sensitive information, make sure to ask the user if they're on a trusted device before enabling persistence.

Important: For the web, offline persistence is an experimental feature that is supported only by the Chrome, Safari, and Firefox web browsers. Also, if a user opens multiple browser tabs that point to the same Cloud Firestore database, and offline persistence is enabled, Cloud Firestore will work correctly only in the first tab.

What you're seeing is the expected behavior until you enable persistence.