Iterate through Firebase ref to load its children - javascript

I want to individually load each child of an object from firebase.
A nonworking snippet of code to better explain the idea is given below:
var userId = firebase.auth().currentUser.uid;
firebase.database().ref('/users/'+userId+"/foo/list").once('value').then(function(list) {
var reffoo = firebase.database().ref().child("/foo/");
for (var i = 0; i < list.length; i++) {
ref = reffoo.child(list[i]);
$scope.foo[ref] = $firebaseObject(ref);
}
});
As per my analysis the issue is, $firebaseObject makes async call to firebase but don't know how to make it work?

One option is to obtain a ref to your collection and iterate over using
data snapshot api i.e.,
var ref = firebase.database().ref('/users/'+userId+"/foo/list");
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
$scope.foo[childKey] = childData;
});
});
If you want to maintain actual angularFire reference to an object then $firebaseArray comes to help:
var list = $firebaseArray(ref);
// add an item
list.$add({ foo: "bar" }).then(...);
// remove an item
list.$remove(2).then(...);
// make the list available in the DOM
$scope.list = list;

Related

I am making a firebase-database list and don't know how to make it remove items from the database

I am pretty new to Javascript, a couple of months in. Essentially, I am trying to make a simple online-based shared shopping-list for a class. I can add to the database, I can show the items as a list, right now my issue is how to remove. I have given the buttons the keys of the database entry they are attached to, as ID, hoping that that would work, but I can't find a way to use the ID. As you can see, i've been testing it by seeing if I can console.log the key, but no luck so far. I've seen a dozen videos and tried dozens of guides, and I hope you can help me; How to I make it so when I click the button, the corresponding entry in the database is deleted? Sorry that the code is a bit of a mess, right now, it is mostly strung together from old code and guides.
var database = firebase.database();
var ref = database.ref('Varer');
ref.on('value', gotData, errData);
function gotData(data){
document.getElementById('Liste').innerHTML = "";
var kbdt = data.val();
var keys = Object.keys(kbdt);
for (var i = 0; i < keys.length; i++){
var k = keys[i];
var kob = kbdt[k].varer;
var btn = document.createElement('button');
var btnText = document.createTextNode('Done')
var opg = document.createElement('li');
var opgnvn = document.createTextNode(kob);
opg.appendChild(opgnvn);
btn.appendChild(btnText);
opg.appendChild(btn);
opg.setAttribute('id', k);
opg.setAttribute('class', 'button');
document.getElementById('Liste').append(opg);
btn.addEventListener('click', function(){
deleteTask(this.id)});
}
}
function errData(err){
console.log('error!');
console.log(err);
}
function deleteTask(id) {
console.log(id);
}
function Indkob() {
var nyVare = document.getElementById('tilfoj').value;
document.getElementById('Liste').innerHTML = "";
var data = {
varer: nyVare
}
var result = ref.push(data);
console.log(result.keys);
}

Retrieving Data From Firebase Not Displaying Correctly in Console

I'm able to display the correct data from my Firebase child in the console with the following code:
var ref = firebase.database().ref('requests');
ref.on('value', gotData, errData);
function gotData(data) {
var scores = data.val();
console.log(scores);
}
Which displays the following in the console:
So when I try to use this snippet of code to retrieve the email:
function gotData(data) {
var scores = data.val();
console.log(scores);
var keys = Object.keys(Email);
console.log(keys);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var emails = email[k].email;
console.log(emails);
}
}
it's displaying the following error:
but I'm not fully understanding why I'm getting this error when this is very similar to other peoples solution.
Anyone know why I'm getting this error when there is an actual value for the email key?
To get the email simply to do this:
var ref = firebase.database().ref('requests');
ref.on('value', function(snapshot) {
snapshot.forEach(function(child) {
var datas = child.val();
var email=child.val().Email;
});
});
Assuming you have this database:
requests
randomid
Email: email_here
You need to be iterating inside the randomid to be able to access the property Email

How to traverse through the auto key generated by firebase push() in React Native?

I have created a search that queries the discogs api for Albums. when I swipe the Album it gets pushed into the realtime database. Firebase auto generates keys for each item pushed which is great, but I am not sure how to handle these keys. How do I get the image url into my require statement? I
here's the function that pushes to the database.
saveToCollection() {
const myFirebaseRef = firebase.database().ref();
myFirebaseRef.push({
albums: `${this.props.album.cover}`
});
}
Any help would be greatly appreciated!
Update with code from comments:
componentWillMount() {
const rootRef = firebase.database().ref();
const albumRef = rootRef.child('albums');
albumRef.once('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
var childKey = childSnapshot.key;
var childData = childSnapshot.val(); // ... this.setState({albums: childKey.childData}) }); }); }// This is just a sample script. Paste your real code (javascript or HTML) here.
if ('this_is' == /an_example/) {
of_beautifier();
} else {
var a = b ? (c % d) : e[f];
}
You could iterate over the firebase auto generated keys using for...in and push each value in into an array then use the Mustache {{#.}} ... {{/.}} tag pair to iterate over each object in the array.
let arr = [];
for(let autoKey in childData){
arr.push(childData[autoKey]);
}
let tpl = '{{#.}} {{albums}} {{/.}}';
Mustache.render(tpl, arr);

How to get only one element from an array (firebase database, nodejs)

If I use limitToLast(1), then I still get an object, with one key-value pair. To get the value, I use this code:
db.ref('/myarray').limitToLast(1).once('value').then(function(snapshot) {
var result = snapshot.val();
var lastElem;
var lastKey;
for(var i in result) {
lastElem= result[i];
lastKey = i;
break;
}
...
});
It works, but I think I do it wrong. But haven't found any better solution in the docs. How should I load only one element?
The database looks like this:
When using Firebase queries to get children, use the "child_added" event:
db.ref("/myarray")
.orderByKey() // order by chlidren's keys
.limitToLast(1) // only get the last child
.once("child_added", function(snapshot) {
var key = snapshot.key;
var val = snapshot.val();
...
});

Javascript variable is an array of objects but can't access the elements

I am using Firebase database and Javascript, and I have code that will get each question in each category. I have an object called category will contain the name, the questions, and the question count, then it will be pushed into the list of categories (questionsPerCategory). Inside the the callback function I just do console.log(questionsPerCategory). It prints the object (array) that contains the categories and questions. Now my problem is that when I do console.log(questionsPerCategory[0]) is says it's undefined, I also tried console.log(questionsPerCategory.pop()) since it's an array but it's also undefined. Why is that? Below is the code and the image of the console log. Additional note: CODE A and C are asynchronous, CODE B and D are synchronous.
this.getQuestionsForEachCategory = function(callback, questions, questionsPerCategory) {
var ref = firebase.database().ref('category');
var questionRef = firebase.database().ref('question');
console.log('get questions for each category');
// CODE A
ref.once("value", function(snapshot) {
// CODE B
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var category = {
category_name: childData.category_name
};
// CODE C
questionRef.orderByChild("category_name").equalTo(childData.category_name).once("value", function(questionSnapshot){
var count = 0;
var q = [];
// CODE D
questionSnapshot.forEach(function(childQuestionSnapshot) {
var questionObj = childQuestionSnapshot.val();
count++;
questions.push(questionObj.question);
q.push(questionObj.question);
});
category.questions = q;
category.questionCount = count;
questionsPerCategory.push(category);
});
});
callback(questionsPerCategory);
});
};
The callback(questionsPerCategory); should happen when all async calls are finished.
Right now the questionsPerCategory is not ready when the callback is called.
I would use Promise API to accomplish this.
Depending on the Promise library you are using, this can be accomplished in a different ways, e.g. by using bluebird it looks like you need map functionality.
Try this code:
this.getQuestionsForEachCategory = function(callback, questions) {
var ref = firebase.database().ref('category');
var questionRef = firebase.database().ref('question');
console.log('get questions for each category');
var questionsPerCategory = [];
// CODE A
ref.once("value", function(snapshot) {
// CODE B
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var category = {
category_name: childData.category_name
};
// CODE C
questionRef.orderByChild("category_name").equalTo(childData.category_name).once("value", function(questionSnapshot){
var count = 0;
var q = [];
// CODE D
questionSnapshot.forEach(function(childQuestionSnapshot) {
var questionObj = childQuestionSnapshot.val();
count++;
questions.push(questionObj.question);
q.push(questionObj.question);
});
category.questions = q;
category.questionCount = count;
questionsPerCategory.push(category);
});
callback(questionsPerCategory);
});
});
};

Categories

Resources