Txo
Txo

Reputation: 37

How to add Firebase data to Array JavaScript

enter image description here

I have a Firebase database, and I'm trying to add the data to an Array.

The problem, is that it's putting every value of the snapshot in the Array at index 0.

var id = snap.child("id").val();

var emptyArray = [];
emptyArray.push(id);
console.log(emptyArray[0]);

Result: 1 2 3 4 5 6

var emptyArray = [];
emptyArray.push(id);
console.table(emptyArray[1]);

Result: undefined

The loop I'm trying to use

for(var i = 0; i < id.length; i++) {
       emptyArray.push(id[i]);
   }

I've just tried making the id an array to work with the loop but still it's returning all data at index 0

var id = [snap.child("id").val()];

Full code for Firebase

$(document).ready(function(){
var pageNumber = document.getElementById("pageNumber").innerHTML;
var rootRef = firebase.database().ref().child("data/p"+pageNumber+"/users/");
rootRef.on("child_added", snap => {
   var id = [snap.child("id").val()];

   var emptyArray = [];
   for(var i = 0; i < id.length; i++) {
       emptyArray.push(id[i]);
   }
    console.log(typeof emptyArray[0]);    
 })
});

Edit: I'm very new to JavaScript/HTML

Edit 2: Added a loop I just tried

Edit 3: Tried making the id an Array

Edit 4: Full code

Upvotes: 0

Views: 262

Answers (1)

notquiteamonad
notquiteamonad

Reputation: 1169

Okay, so what I think's happening is this event is calling on the child_added event so the snapshot snap is just the snapshot for one user.

Every time you get the result for one user you create the new array and just put in the ID for that user, then it goes out of scope at the end of the on callback.

Instead, you need to create the array outside the callback and just add to it, like so:

$(document).ready(function(){
var pageNumber = document.getElementById("pageNumber").innerHTML;
var rootRef = firebase.database().ref().child("data/p"+pageNumber+"/users/");
var emptyArray = []; // Create the array outside the callback
rootRef.on("child_added", snap => {
   var id = snap.child("id").val();
   emptyArray.push(id); // Add the user's ID to the array
 });
console.log(emptyArray); // -> [1, 2, 3, 4, 5, 6]
});

Upvotes: 1

Related Questions