Last active
September 21, 2023 20:28
-
-
Save katowulf/6383103 to your computer and use it in GitHub Desktop.
Get only new items from Firebase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// assumes you add a timestamp field to each record (see Firebase.ServerValue.TIMESTAMP) | |
// pros: fast and done server-side (less bandwidth, faster response), simple | |
// cons: a few bytes on each record for the timestamp | |
var ref = new Firebase(...); | |
ref.orderByChild('timestamp').startAt(Date.now()).on('child_added', function(snapshot) { | |
console.log('new record', snap.key()); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pros: works? | |
// cons: fetches entire record set, requires discarding the first record | |
// credits: http://stackoverflow.com/questions/12850789/is-there-a-way-to-know-in-what-context-child-added-is-called-particularly-page/12851236#12851236 | |
var ref = new Firebase(...); | |
ref.once("value", function(snap) { | |
//TODO: display initial state... | |
// Object.keys not supported in IE 8, but has a polyfill: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys | |
var keys = Object.keys(snap.val()||{}); | |
var lastIdInSnapshot = keys[keys.length-1] | |
ref.orderByKey().startAt(lastIdInSnapshot).on("child_added", function(newMessSnapshot) { | |
if( snap.key() === lastIdInSnapshot ) { return; } | |
console.log('new record', snap.key()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pros: does not fetch entire record set | |
// cons: triggers child_removed events when last item changes, grabs the last record which needs to be ignored | |
var first = true; | |
var ref = new Firebase(...); | |
ref.limitToLast(1).on("child_added", function(snap) { | |
if( first ) { | |
first = false; | |
} | |
else { | |
console.log('new record', snap.key()); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if we were to use ref.push().key to put a new entry on ref, it would be stored as the last child.So, using second parameter of startAt function, we retrive childs with key greater than or equal to ref.push().key
https://firebase.google.com/docs/reference/js/firebase.database.Query#startat
yes, https://firebase.google.com/docs/database/admin/save-data#push-vs-transaction