2. Lists

WARNING! Lists on Firebase work in a crazy way.

The code below adds temperature data (got from the temperature input field) to a list and keeps that list on Firebase. I didnt want to show the whole list, so I made the code only show the last 10 temperatures. The temperatures are shown in reverse order i.e. the last temperature to be added to the list is at the top.

<!DOCTYPE html>
 <script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script>
 <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
 <input type='text' id='tempInput' placeholder='Temperature'>
 <button type="button" onclick="doButtonAction()">run</button>
 <div id="tempOutput"></div>
 // Initialize Firebase
 var config = {
 apiKey: "AIzaSyC1Bv7DRQxzUGlRqw7PcGNFhxIxI3pfj1A",
 authDomain: "temp-data-62b59.firebaseapp.com",
 databaseURL: "https://temp-data-62b59.firebaseio.com",
 storageBucket: "",
 var temperatureDataRef = firebase.database().ref("temperature");
 function doButtonAction(){
 var temp = $('#tempInput').val();
 temperatureDataRef.push({temperature: temp});
 temperatureDataRef.limitToLast(10).on('child_added', function(snapshot) {
 var output = snapshot.val();

So here’s the weird bit about how Firebase handles lists. This bit of code that is supposed to run when another element (a.k.a. Child in Firebase talk) is added:

 temperatureDataRef.limitToLast(10).on('child_added', function(snapshot) {
 var output = snapshot.val();

But that’s not exactly correct. When you start your program, chances are you were using it before and added some children to the list already. When you start your program again (after having added the children before) Firebase pretends that  it is running since the first child was added to the list, so it will run the above code as many times are there are children in the list. The result is that, if you don’t put a limit on the number of children shown, all the children in the list will be presented. We put a limit of 10 so we only get 10 children form the list.

You will see in the above snippet of code that I used the limitToLast() method. There are lots more methods you can use on lists here.