I use PouchDB to store data offline and synchronize with a remote CouchDB database when the application goes online. It works well if the app is launched online: PouchDB triggers the pause
event when the connexion is interrupted and continues when the connexion comes back. Here is a sample code:
localDB.replicate.to(remoteDB, {
live: true,
retry: true
}).on('paused', function (info) {
// replication was paused, usually because of a lost connection
}).on('change', function (change) {
// yo, something changed!
}).on('active', function (info) {
// replication was resumed
}).on('error', function (err) {
console.log(err);
// totally unhandled error (shouldn't happen)
})
But when the application is launched offline, an error is encountered (Failed to load resource: net::ERR_ADDRESS_UNREACHABLE
)
the remote database can't be accessed and PouchDB triggers an error
event ("Database encountered an unknown error"
, status 500). Even if the connexion comes back, the replication will not work.
Question:
Is there a way to make the replication work even if the application is launched offline (for example by making the pause
event comes first even if there is no access to the remote database yet)?
UPDATE: Thanks to nlawson for the answer! I just had to add the remote database creation in the function to make it work:
function retryReplication() {
var remoteDB = new PouchDB('http://129.199.80.62:5984/remotedb');
localDB.replicate.to(remoteDB, {
live: true,
}).on('paused', function (info) {
// replication was paused, usually because of a lost connection
}).on('change', function (change) {
// yo, something changed!
}).on('active', function (info) {
// replication was resumed
}).on('error', function (err) {
setTimeout(retryReplication, 5000);
// totally unhandled error (shouldn't happen)
});
};
This should probably be a bug report on Github rather than a question on StackOverflow. :) I filed it here.
The retry
replication should definitely work regardless of whether it starts in offline or online mode. I'm sorry you ran into this bug!
In the meantime, you can avoid the retry
option and do the retry replication yourself. You can find a description of how to do that here.
Update: this bug was fixed in PouchDB 3.6.0.
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