0

I have this code:

 firebase.initializeApp(config);
 var database = firebase.database();
 var messages = database.ref('messages');
 messages.limitToLast(100).on('child_added', function(snapshot) {
     var data = snapshot.val();
     if (data.random != random_value) {
         show(data.message);
     }
 });

and it get executed when new message is added as well on init. How can I distinguish between new message and old messages?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • 1
    Knowing what defines "old" and "new" to you is the key to coming up with a solution. Here are a few good previous discussions: [1](https://stackoverflow.com/q/18270995), [2](https://stackoverflow.com/q/19114134), [3](https://stackoverflow.com/a/27693310), [4](https://stackoverflow.com/a/12851236). – Frank van Puffelen Aug 19 '17 at 17:15
  • 1
    @FrankvanPuffelen thanks, I've mark this one as duplicate of the first one, which solve the issue for me. – jcubic Aug 19 '17 at 17:33

1 Answers1

1

On child_added it will always return all messages. On the first run it will return all those that already are in your database and after that it will just trigger when something is added that was not there before.

So if you just want new messages, you simply have to mark them as read in your database and go on from there.

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402