PouchDb first time syncing onchange event spaming

763 Views Asked by At

I'm developing an offline web app using pouch db.

First time user launch the app local db sync with couch db, and the onchange event spams a lot (45 times for 37 docs), so my functions bounded to this event do their job in wrong ways because local db is incomplete, as well it is not optimized because my functions do the work 45 times for nothing ! The onchange event triggers lot of times before couch db as been fully replicated to pouch db.

Is there a way to know when the local db is really ready, when data are same as couch db ? I'm using live changes option.

I have this problem only for first launch when local db is empty.

Current solution (seems to be bad): I noticed pause event trigger two times consecutively when all changes are loaded, so I detect if my db is ready like this:

var dbReady = false;

db.sync(remoteDb, options).on('paused', function () {

    if (!dbReady) {
        // Db not ready to use
        console.log("Pouch: Waiting...");
        dbReady = true;
    }
    else {
        // Db ready to use !
        console.log("Pouch: Ready...");
        // Some code...
    }

}).on('active', function () {
    console.log("Pouch: Syncing...");
    dbReady = false;

}).on('error', function () {
    console.log("Pouch: Offline...");
});
2

There are 2 best solutions below

1
On

Maybe try on complete event handler: sync explained

}).on('complete', function (info) {
     // handle complete
})

Good luck

0
On

Based on my limited experience, i will trigger a loading animation on first sync and stop the animation when the db sync is paused. So when it detect changes, it will trigger the loading animation again in

}).on('change', function (info) {
 // trigger loading animation

}) and stop the animation when the sync is paused.