Last active
September 22, 2016 07:33
-
-
Save blackbing/f1fd8abedf9344938deb0fc08a5afce9 to your computer and use it in GitHub Desktop.
firebase fetch latest and older data by limit number example
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>Firebase get limited latest and previous data </title> | |
<script src="https://www.gstatic.com/firebasejs/3.4.0/firebase.js"></script> | |
</head> | |
<body> | |
<div> | |
<button id="latest">fetch latest</button> | |
<button id="more">fetch older</button> | |
<ul id="list"> | |
</ul> | |
</div> | |
<script> | |
// Initialize Firebase | |
var config = { | |
apiKey: "", | |
authDomain: "", | |
databaseURL: "", | |
storageBucket: "", | |
messagingSenderId: "" | |
}; | |
var app = firebase.initializeApp(config); | |
var root = app.database().ref('comments'); | |
var limit = 3; | |
var messages = []; | |
var endAt = null; | |
document.querySelector('#latest').addEventListener('click', function() { | |
root.limitToLast(limit).on('child_added', function(snapshot, previousChildKey) { | |
console.log(previousChildKey); | |
var data = snapshot; | |
if (!endAt) { | |
endAt = previousChildKey; | |
} | |
messages.push(data.val()); | |
renderList(); | |
}); | |
}); | |
document.querySelector('#more').addEventListener('click', function() { | |
// fetch limit +1 because the data will contain endAt | |
root.endAt(null, endAt).limitToLast(limit+1).on('value', function(snapshot) { | |
var dataArray = []; | |
var currentEndAt = null; | |
snapshot.forEach(function(data) { | |
if (data.key !== endAt) { | |
dataArray.push(data.val()); | |
} | |
if (!currentEndAt) { | |
currentEndAt = data.getKey(); | |
} | |
}); | |
// finally update endAt | |
endAt = currentEndAt; | |
// concat data | |
messages = dataArray.concat(messages); | |
renderList(); | |
}); | |
}); | |
function renderList() { | |
var html = messages.map(function(message) { | |
return '<li>' + JSON.stringify(message) + '</li>'; | |
}); | |
document.querySelector('#list').innerHTML = html.join(''); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment