Valentine Valentine - 1 year ago 81
Javascript Question

Looping through a collection of Firebase Database records

I am trying to iterate a collection of items from Firebase Database and later store it in my local storage, but its seems I can't figure out what wrong. I have actually read the documentation but still haven't figured out why the code doesn't work.

Below is my code:

dataRef.once("value", function(snapshot) {

snapshot.forEach(function(childSnapshot) {

var hymn_no = childSnapshot.val().hymn_no;
var hymn_category = childSnapshot.val().hymn_category;
var hymn_key = childSnapshot.val().hymn_key ;
var hymn_title = childSnapshot.val().hymn_title;
var hymn_verses = childSnapshot.val().hymn_verse;
var hymn_chorus = childSnapshot.val().hymn_chorus;
var hymn_author = childSnapshot.val().hymn_author;


var hymns = [
new Hymn({
"hymn_no": hymn_no,
"hymn_category": hymn_category,
"hymn_key": hymn_key,
"hymn_title": hymn_title,
"hymn_chorus": hymn_chorus,
"hymn_verses": hymn_verses,
"hymn_author": hymn_author,
localStorage.setItem("Hymns", JSON.stringify(hymns));
return JSON.parse(localStorage.getItem("Hymns"));


Answer Source

You are making a new array with one hymn in it and storing that new array every iteration of the loop.

Since it is stored in same storage key it will overwrite anything else stored there

That means you would only and up with only the last hymn stored.

Create the array outside the loop... push new items to that array inside the loop...then after loop completes, store the whole array once

dataRef.once("value", function(snapshot) {
          var hymns = [];
          snapshot.forEach(function(childSnapshot) {
               var item = new Hymn(...);
               // push each new item to array
          // loop done, store data
          localStorage.setItem("Hymns", JSON.stringify(hymns));
          // return array
          return hymns;    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download