Can a variable be declared within the path references of the Firebase database?

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/

Answer №1

Based on how I interpreted your inquiry, you may be looking for a solution similar to the following:

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    let userReference = firebase.database().ref('users').child(user.uid);
    let buildingsReference = userReference.child('buildings');
    // proceed with manipulating these references as needed
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it not possible to utilize async/await with MongoDB Model, despite it yielding a Promise?

Currently, I am facing an issue with a function in my code that is supposed to retrieve a user's inventory and then fetch the price property of each element using data from a Price Collection. Below is a snippet of the function (not the entire thing, ...

Spinning Earth orbits around the Sun

My goal is to create a 3D Solar system, starting with the Sun and Earth using THREE.SphereGeometry() var sphere2 = new THREE.Mesh(new THREE.SphereGeometry(50, 100, 100), new THREE.MeshBasicMaterial({side: THREE.DoubleSide, map:txt2})); sphere2.position.se ...

Avoid reloading the page in PHP when the browser back button is clicked

I've built an HTML form where the values are passed to a second page using POST method. On the second page, I have an edit button that, when clicked, redirects back to the HTML form page with the user's typed values. However, my dilemma is figuri ...

Leverage the power of AJAX and PHP to securely save comments for future

I have coded a JavaScript function that uses POST and GET methods to send comments from an input field and retrieve them when the page reloads. However, I am unsure of how to handle the data after it is sent in order to save it and access it again later. E ...

Testing a service resolution in a controller through unit testing

As I attempt to create a test for my home module, I keep encountering an error that reads "unknown provider: service." Interestingly, when I modify resolveSomething in my home module to output a string, the app functions as expected, indicating that the re ...

Storing TypeScript functions as object properties within Angular 6

I am working on creating a simplified abstraction using Google charts. I have implemented a chartservice that will act as the abstraction layer, providing options and data-source while handling the rest (data retrieved from a REST API). Below is the exist ...

"Step-by-Step Guide: Activating Tab Functionality in J

I'm facing an issue here - I've been attempting to log the event's key code and I keep getting key number (9). I believe my script isn't disabling event.keyCode properly, hence the key function remains active. What changes should I make ...

Error Encountered with Nested Angular Material Tabs

Is there a way to prevent changes made to the upper tab in md-align-tabs attribute from affecting the inner tab when one tab is nested inside another using md-tabs? If so, how can I achieve this? <md-content layout="column" layout-fill> <md-ta ...

Incorporate a gradient into a Vuetify v-card background image

<v-card :img="require('@/core/assets/homeBg.png')" > </v-card> Although the image is currently displaying properly, I am interested in finding a way to add a gradient effect to it. (Specifically, I aim to darken the imag ...

Check out the ViewUI Vue.js component that expands to reveal more content!

Is there a simple component to create the expand/collapse button with a blur effect like in all the demos? I see it used across different variations of the demos and am wondering if there is a specific component or demo showcasing how to achieve this effec ...

Problems with the functionality of the remote feature in Twitter Bootstrap Modal

Utilizing Twitter Bootstrap, I aim to retrieve HTML from another page and inject it into the modal on my current page. This led me to create a JavaScript function to facilitate this process. Within my 'index.php' file, I include the following: ...

How can I save or export an image file containing HTML content?

Currently, I am working on a project where I am generating dynamic HTML content. My goal is to be able to export or save this HTML content as an image file using PHP, jQuery, and JavaScript (or any other method if applicable). Can anyone help with the im ...

Utilizing an array for assigning values in conditional statements

I have been experimenting with toggling a CSS style on a couple of elements using an if statement. Currently, I have it working with several if statements, but I believe it can be simplified by utilizing an array with the values and just one if statement. ...

Execute code after selecting the link

To simplify my question, I will provide an example: Suppose I have two sample pages that I want to demonstrate: Page 01 <script> var demo = 'X1'; alert(demo); $( document ).ready(function() { $("#cont").on("click" ...

"Building your own utilities in Nuxtjs: A step-by-step guide

Currently, I am using Nuxtjs version 2.15.4 and I am looking to update my Utils functionality. Currently, I am using a mixin for my utils but I would like to implement something similar to the following code snippet: import {func1 , func3} from '~/plu ...

Incorporating components into Vue while utilizing Flask poses a challenge

Currently, I am working on a project that involves Flask and Vue. I am attempting to add a carousel to my website, but I am running into difficulties with creating and importing components for Vue when following tutorials. Here is my current file structure ...

Preview not showing CSS changes properly

1) I am encountering an issue with displaying CSS in a form preview tab. Despite setting the CSS, it does not reflect on the fields after clicking the preview button. 2) Are there alternative methods to open the tab in a new window rather than opening it ...

NextAuth.js in conjunction with nextjs version 13 presents a unique challenge involving a custom login page redirection loop when using Middleware - specifically a

I am encountering an issue with NextAuth.js in Nextjs version 13 while utilizing a custom login page. Each time I attempt to access /auth/signin, it first redirects to /login, and then loops back to /auth/signin, resulting in a redirection loop. This probl ...

Can you reference document.styleSheets[].cssRules[] by specifying a rule name?

I am trying to modify a specific class property value in JavaScript without using an integer as a pointer or looping through all classes to find a matching selectorText value. This is specifically for changing the language displayed on the webpage. <s ...

The current status of the ajax call is set to 0

I am currently attempting to retrieve information from a remote server on my local machine. The readyState seems to be fine, equal to 4. However, the status is consistently showing as 0 instead of 200. When I click the button, it doesn't return anythi ...