As far as I could find out, PouchDB has no event to inform us that the syncing was stopped because of a disruption in the internet connection. I did a small hack to solve this.
When the sync is happening properly, and you make a change to your local PouchDB, the order in which events are fired is:
- active
- change
- paused
However, when the internet is broken, the order is:
- active
- paused
There is no change event fired when syncing with the remote DB isn't taking place.
So, what I've done is made two flags for the active and change events , pouchDbSyncActiveEvent
and pouchDbSyncChangeEvent
respectively, and initialized both as false
. Turn pouchDbSyncActiveEvent
to true
in the callback for the 'active'
event. This will run regardless of whether there is internet or not. Turn pouchDbSyncChangeEvent
to true
in the callback for the 'change'
event. If there is no internet, this won't run and pouchDbSyncChangeEvent
will still remain false
, and the 'paused'
event will be fired soon after. This informs us that the syncing was stopped.
Code:
let pouchDbSyncActiveEvent = false
let pouchDbSyncChangeEvent = false
localPouchDb.sync(remoteCouchDb, {
live: true,
retry: true
})
.on('active', (change) => {
pouchDbSyncActiveEvent = true
})
.on('change', (change) => {
pouchDbSyncChangeEvent = true
})
.on('paused', (info) => {
if(pouchDbSyncActiveEvent == true && pouchDbSyncChangeEvent == false){
// Gotcha! Syncing with remote DB not happening!
}
else {
// Everything's ok. Syncing with remote DB happening normally.
}
pouchDbSyncActiveEvent = false
pouchDbSyncChangeEvent = false
})
Note:
You can write the .on
event listener methods in the order you wish, but it is good to write them in the order they are executed :)