DThink DThink - 11 months ago 86
Javascript Question

Only listent to last children by date in Firebase

In my app, I use this code to listen only to the children added after the current time:

var start = new Date().getTime();

firebase.database().ref(path).orderByChild('created').startAt(start).on('child_added', function(value){

In the browser, this method works well. I see the child only if I start to add it after the current time.

In the smartphone, this method doesn't work. It works only if I start to add a children after a certain amount of seconds. I think that this happens because the current time of the smartphone is different with the current time of the server.

Is there any way to fix this without having to take the last element?

Answer Source

If the clock on your phone is off, this will not work reliably.

Firebase detects the offset of the local clock to the server time and exposes this in a value .info/serverTimeOffset. You can use this to correct for the clock skew as explained in the documentation on clock skew:

var offsetRef = firebase.database().ref(".info/serverTimeOffset");
offsetRef.on("value", function(snap) {
  var offset = snap.val();
  var estimatedServerTimeMs = new Date().getTime() + offset;

Read the linked documentation for a full explanation.