PaulaMacT
PaulaMacT

Reputation: 77

firebase last record only

I want to append only the last record added to firebase to a table. I tried

firebase().database().ref()
  .orderByChild("dateAdded")
  .limitToLast(1)
  .on("child_added", function (snapshot) {
    $('.table').append(
      "<tr><td>" + snapshot.val().train + 
      "</td><td>" + snapshot.val().destination + 
      "</td><td>" + snapshot.val().frequency + 
      "</td></tr>"
    );
  });

The first time I add a new entry it works but the second new entry is added twice, third - three times, etc.

Is there a way that will only add each new entry only once?

Upvotes: 7

Views: 9038

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

It seems you need to read your data only once and not every time data is changed at the specified database reference

So you should do:

firebase().database().ref()
  .orderByChild("dateAdded")
  .limitToLast(1)
  .once("child_added....

Have a look at the documentation: https://firebase.google.com/docs/database/web/read-and-write#read_data_once

Upvotes: 13

Related Questions