7

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?

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. This worked perfectly! I tried to up-vote your answer but I am new to coding and don't have enough cred to make the ticker go up.
@PaulaMacT :-) I think that you should be able to accept the answer (clicking the grey checkmark, which will then become green), see superuser.com/help/accepted-answer Thanks and welcome to SO.
@ RenaudTarnec checked :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.