Julien Tanay Julien Tanay - 1 year ago 179
AngularJS Question

How to sync offline database with Firebase when device is online?

I'm currently using angularJS and phonegap to build a test application for Android / iOS.

The app use only text data stored in a Firebase database. I want the app to have its own local database (used when the device is offline) and sometime (when the device is online)
sync with a Firebase database.

The offline mode uses the storage API of phonegap/cordova. Could I just check the device's online state and backup the online database periodically ?

Any clues on how I can achieve this ? Last time a similar question was asked, the answer was "not yet"... (here)... because it focused on a hypothetical Firebase feature.

Answer Source

If Firebase is online at the start and loses its connection temporarily, then reconnects later, it will sync the local data then. So in many cases, once Firebase is online, you can simply keep pushing to Firebase during an outage.

For true offline usage, you will probably want to monitor the device's state, and also watch .info/connected to know when Firebase connects.

new Firebase('URL/.info/connected').on('value', function(ss) {
   if( ss.val() === null ) /* firebase disconnected */
   else /* firebase reconnected */

The way to achieve this with the current Firebase toolset, until it supports true offline storage, would

  1. keep the local data simple and small
  2. when the device comes online, convert the locally stored data to JSON
  3. use set() to save the data into Firebase at the appropriate path

Additionally, if the app loads while the device is offline, for some reason, you can "prime" Firebase by calling set() to "initialize" the data. Then you can use Firebase as normal (just as if it were online) until it comes online at some point in the future (you would also want to store your local copy to handle the case where it never does).

Obviously, the simpler the better. Concurrent modifications, limits of local storage size, and many other factors will quickly accumulate to make any offline storage solution complex and time consuming.