I have three nodes in my firebase db: users
, projects
and user-projects
.
I want to populate a <select>
with the names of the projects, and select one option based on the preferences of the user. To achive that I follow the next steps:
- Get the data of the authenticated user:
users/uid
. - Get the projects associated with that user:
user-projects/uid
. - Transform one object with keys to an array of strings.
- Perform one request per key and use
$.when.apply($, requests)
to wait all the results (to keep the order). - Finally show the select with options and pre-select one of them.
My question is, really all of these steps are neccesary?
If I store the name of the projects in user-projects
I can avoid the last 3 steps, but in that case, I have to update more nodes when a project changes (and I really don't want to do that).
Also I was looking for examples that use firebase with one JS framework (react.js, vue.js), but it seems that the asynchronous requests are made with other libraries, independent of those view frameworks.
I am using the next lines of code:
// Authenticated user
var user = firebase.auth().currentUser;
// General reference to the real time db
var ref = firebase.database().ref();
// Request the user data
ref.child('users/'+user.uid).once('value').then(function(snapshot) {
var user_data = snapshot.val();
// console.log(user_data);
// Global variable to store the id of the selected project
project_selected_key = user_data.project_selected;
// Get associated projects
return ref.child('user-projects/'+user.uid).once('value');
}).then(function (projectsSnapshot) {
// projectsSnapshot.val() != project_keys
var project_keys = [];
projectsSnapshot.forEach(function (e) {
project_keys.push(e.key);
});
// it is not possible :/
// return ref.child('projects').children(project_keys).once('value');
// one request per key
var requests = [];
var results = [];
project_keys.forEach(function (project_key) {
var request = ref.child('projects/'+project_key).once('value', function (snapshot) {
results.push(snapshot.val());
});
requests.push(request);
});
// wait until all requests are complete
$.when.apply($, requests).then(function() {
console.log(results);
}, function (error) {
console.log('One request has failed');
});
}, function (error) {
// Something went wrong
console.error(error);
});