0

I am trying to redefine all my apps database references so that I can write a specific set of of firebase rules (I need to add buildings and depts nodes inside the user node – read why: What is the best practice to write the rules of Firebase in a situation like this? ).

I am using a firebase-config.js and exporting all my app's database references to the app's components so hopefully if I change this path I don't have to refactor the code on all the app's components.

I am trying to do it with a function (on my 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');
_// BUT THIS: "buildingsRef" is returning undefined!!! :(
export const buildingsRef = db.ref('users'+ "/" + buildingsRef) //buildingsRef is a variable
export const deptsRef = db.ref('depts');

The buldingsRef variable is returning undefined and it's writing the buildings to an undefined node.

{
  "users" : {
    "6hwNde08Wuaa9bfReR28niSbOsF3" : {
      "name" : "João Alves Marrucho",
      "userEmail" : "joaoalvesmarrucho@hotmail.com"
    },
    "undefined" : {
      "-L9M4lM7oZFfmJKorxjC" : {
        "address" : "",
        "name" : "b1",
        "ownerID" : "6hwNde08Wuaa9bfReR28niSbOsF3"
      }
    }
  }
}

I writing to the node with the following method (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);
}

Any thoughts on why the variable buildingsRef is returning undefined?

Here is my full firebase-config.js file: http://jsfiddle.net/UnXrw/85/

1 Answers1

0

If I understand your question, I think you want something like this:

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    let userRef = firebase.database().ref('users').child(user.uid);
    let buildingsRef = userRef.child('buildings');
    // now do whatever you want with those refs
  }
});
Michael Bleigh
  • 25,334
  • 2
  • 79
  • 85