PouchDB: database replication when the application is launched offline-open source projects pouchdb/pouchdb
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)
});
};