I have three nodes in my firebase db: users , projects and user-projects .
I want to fill out <select> with project names and choose one option based on user preferences. To achieve this, I follow the following steps:
- Get authenticated user data:
users/uid . - Get projects associated with this user:
user-projects/uid . - Convert a single object using keys into an array of strings.
- Execute one key request and use
$.when.apply($, requests) to wait for all results (to keep order). - Finally, show the selection with the parameters and pre-select one of them.
My question is: are all these steps really necessary?
If I store the name of the projects in user-projects , I can avoid the last 3 steps, but in this case I need to update more nodes when the project changes (and I really do not want to do this).
I also searched for examples of using firebase with one JS framework (response.js, vue.js), but it seems that asynchronous requests are executed with other libraries, regardless of this presentation framework.
I use the following 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); });
javascript jquery ajax firebase firebase-database
Jcarlos
source share