In an effort to update my app's database references, I am working on implementing specific Firebase rules that involve adding buildings and depts nodes inside the user node. This decision was prompted by a discussion on best practices for writing Firebase rules in scenarios like this, which you can read about here.
To streamline this process and avoid having to refactor code across all components of the app, I have been utilizing a firebase-config.js file to export all database references to the relevant app components.
I am attempting to achieve this through a function within the firebase-config.js file:
import * as firebase from "firebase";
import { mapState } from 'vuex';
import { store } from './store/store';
var config = {
apiKey: "XXXXXXXX",
authDomain: "XXXXXXXX.firebaseapp.com",
databaseURL: "https://XXXXXXXX.firebaseio.com",
projectId: "XXXXXXXX",
storageBucket: "XXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXX"
};
firebase.initializeApp(config)
export default !firebase.apps.length ? firebase.initializeApp(config) : firebase;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
let userRef = firebase.database().ref('users').child(user.uid);
let buildingsRef = userRef.child('buildings');
}
})();
export const db = firebase.database();
export const usersRef = db.ref('users');
_// HOWEVER, "buildingsRef" is currently returning undefined! :(
export const buildingsRef = db.ref('users'+ "/" + buildingsRef) //buildingsRef is a variable
export const deptsRef = db.ref('depts');
Despite my efforts, the buildingsRef variable is displaying as undefined and data is being written to an undefined node instead of the desired node.
{
"users" : {
"6hwNde08Wuaa9bfReR28niSbOsF3" : {
"name" : "João Alves Marrucho",
"userEmail" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="294346484648455f4c5a44485b5b5c4a41466941465d44484045074a4644">[email protected]</a>"
},
"undefined" : {
"-L9M4lM7oZFfmJKorxjC" : {
"address" : "",
"name" : "b1",
"ownerID" : "6hwNde08Wuaa9bfReR28niSbOsF3"
}
}
}
}
The data is being written using the following method in Vue.js:
addBuilding: function () {
let userId = firebase.auth().currentUser.uid;
let buildingKey = buildingsRef.push().key
this.newBuilding.ownerID = userId;
buildingsRef.child(buildingKey).set(this.newBuilding);
}
If anyone has insights into why the buildingsRef variable is returning undefined, I would greatly appreciate the input.
You can find my complete firebase-config.js file here: http://jsfiddle.net/UnXrw/85/