Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  145] [ 7]  / answers: 1 / hits: 26199  / 10 Years ago, sun, september 7, 2014, 12:00:00

I am trying to get data from two tables like (fetch all users and their details)



tableOne.on('users', function (snapshot) {
userId = snapshot.val().userId; // line 1 (results like 1,2,3,4,5,6)
anotherTable.child('userdetails').child(userId).once('value', function(mediaSnap) {
// result // line 2
});
});


but the problem is line 1 executes first for the 6 times and then line 2 that n times resulting in everytime looking for 'where user id is - 6'...isn't joins supported in Firebase?



Any help is apreciated


More From » firebase

 Answers
3

Your code snippet has a nasty side-effect:



var userId;
tableOne.on('value', function (snapshot) {
userId = snapshot.val().userId; // line 1 (results like 1,2,3,4,5,6)
anotherTable.child('userdetails').child(userId).once('value', function(mediaSnap) {
console.log(userId + : + mediaSnap.val().name);
});
});


You're not declaring userId as a variable, which means that it becomes a global variable in JavaScript. And since the callback function executes asynchronously, there is a good chance that the global values will have changed by the time you need it.



The solution is simply to make userId a local variable of the callback function:



tableOne.on('value', function (snapshot) {
var userId = snapshot.val().userId; // line 1 (results like 1,2,3,4,5,6)
anotherTable.child('userdetails').child(userId).once('value', function(mediaSnap) {
console.log(userId + : + mediaSnap.val().name);
});
});


This will ensure that each value of userId is captured inside the function.


[#69543] Thursday, September 4, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
irvingcarloe

Total Points: 677
Total Questions: 109
Total Answers: 96

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
irvingcarloe questions
Wed, Mar 31, 21, 00:00, 3 Years ago
Tue, Aug 4, 20, 00:00, 4 Years ago
Fri, Jul 3, 20, 00:00, 4 Years ago
;