Can we move the "user" object to the forefront and retrieve it from a location other than the "on.AuthSateChanged(user => .... }" function?

Is there a way to define a ref in vuefire to firebase path that relies on the current User object? Can I bring the "user" object to the top level so it can be accessed outside the "on.AuthSateChanged(user => .... }" block?

firebase-config.js

 import * as firebase from "firebase";

var config = {
    apiKey: "XXXXXX",
    authDomain: "XXXXXX.firebaseapp.com",
    databaseURL: "https://XXXXXX.firebaseio.com",
    projectId: "XXXXXX",
    storageBucket: "XXXXXX.appspot.com",
    messagingSenderId: "XXXXXX"
};
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');
    }
  })();
console.log(buildingsRef); //returning undefined=    

export const db = firebase.database(); 
export const usersRef = db.ref('users');
export const buildingsRef = db.ref('users'+ "/" +buildingsRef)
// I will deal with this later
// export const deptsRef = db.ref('depts');
// export const roomsRef = db.ref('rooms'); 

app.vue

<template>
  <div id="app" class="section">   
    <main>
      <router-view id="main" ></router-view>
    </main>
  </div>
</template>

<script>
import firebase from './firebase-config';
import { buildingsRef } from './firebase-config';
import { deptsRef } from './firebase-config'; 

export default {
  name: 'app',
  data () {
    return {
    }
  },
}
</script>

buildingadd.vue (component)

<template>
  <div class="building">
    <div id="title">
      <h1>{{ initialmsg }}</h1>
    </div>  
    <form id="form" class="form-inline" v-on:submit.prevent="addBuilding">
      <div class="form-group">     
        <p><span> Name: </span><input class="input typename" type="text" placeholder="type name" v-model="newBuilding.name"></p>
      </div>
      <div class="form-group">            
        <p><input type="text" id="buildingAddress" class="form-control" placeholder="Address" v-model="newBuilding.address"></p>
      </div>
      <div class="form-group">            
        <p><textarea id="buildingComments" class="form-control text" cols="40" rows ="6" placeholder="Comments (optional)" v-model="newBuilding.comments"></textarea></p>
      </div>               
      <!-- <button id="addButton" class="button">Add New Space</button> -->
      <router-link  to="/buildings"><button @click="addBuilding" :disabled="!formIsValid">Save</button></router-link>
    </form>
    <!-- <button type="submit" id="updateButton" class="button is-primary"  @click.prevent="updateSpace(newSpace), show = !show" >UPDATE </button>  -->
  </div>
</template>

<script>
import firebase from '../firebase-config';
import { buildingsRef } from '../firebase-config';
import { usersRef } from '../firebase-config';

export default {
  firebase() { 
    return {
    buildings:  buildingsRef,
    users: usersRef,
    }
  },
  name: 'buildingsadd',
  data () {
    return {
      initialmsg: "Add building's details:",
      newBuilding: {
        name: '',
        address: '',
        comments: '',
        ownerID: '',
      }
    }
  },
  methods: {
    setUser() {
        this.$store.dispatch('setUser');
      },
    addBuilding: function () {
      let userId = firebase.auth().currentUser.uid;
      let buildingKey = buildingsRef.push().key
      this.newBuilding.ownerID = userId;
      buildingsRef.child(buildingKey).set(this.newBuilding);
      usersRef.child(userId).child('isAdmin').child(buildingKey).set(true);
    },    
  },
  computed: {
    formIsValid() {
      return this.newBuilding.name !== '';
    },    
  },
}

If you have an answer to this question, it would greatly help me solve my specific problem. How to constrain read/write rules to the users that create the nodes while keeping this structure?

Your assistance is highly appreciated. Thank you!

Answer №1

To easily access it, just append it to the window object.

window.userRef = userRef;

For example:

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    let userRef = firebase.database().ref('users').child(user.uid);
    window.userRef = userRef;
    let buildingsRef = userRef.child('buildings');
    // userRef contains the user uid 
  }
});

console.log(userRef); // will no longer be undefined as long as this is called after the `onAuthStateChanged` response. Thanks for the tip @EmileBergeron

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

How is it possible that this component is able to work with slotting without needing to specify the slot name

I have created two Web Components using Stencil.js: a Dropdown and a Card. Within my Dropdown, the structure is as follows: <div class='dropdown'> <slot name="button"/> <slot/> </div> The nested chil ...

The necessary attribute is malfunctioning. (HTML)

I am currently working on a signup page utilizing HTML and JavaScript. Everything was running smoothly until I added a function to navigate the user to the next page. The issue arises when the textboxes are left blank; upon clicking the button, the user is ...

Can the npm install process impact a Laravel project?

Currently tackling a Laravel project and planning to incorporate Vue.js for its client-side scripting. During my research online, I came across the need to utilize the npm install command. I'm curious if running this command will have any impact on th ...

Elements recognized worldwide, Typescript, and a glitch specific to Safari?

Consider a scenario where you have a select element structured like this: <select id="Stooge" name="Stooge"> <option value="0">Moe</option> <option value="1">Larry</option> <option value="2">Curly</option ...

Exploring various ways to implement HTTP GET requests within the PrimeVue DatatableUsing a mix

I am facing a challenge where I need to use different GET requests to populate my Datatable with data from separate tables in the Database. Despite trying different approaches, I am unable to figure out how to make this work successfully. I have realized t ...

Looking to display database information using javascript

Currently, I am working on a project involving PHP code where I retrieve variables from an input and utilize AJAX. Here is the code snippet: $.ajax({ type: "GET", url: "controller/appointment/src_agenda.php", data: { function: "professional", ...

Exploring arrays and objects in handlebars: A closer look at iteration

Database Schema Setup var ItemSchema = mongoose.Schema({ username: { type: String, index: true }, path: { type: String }, originalname: { type: String } }); var Item = module.exports = mongoose.model('Item',ItemSchema, 'itemi ...

What is a more efficient method for verifying the value of an object within an array that is nested within another object in JavaScript?

Is there a more efficient way to check for an object in an array based on a property, without having to go through multiple checks and avoiding potential errors with the ? operator? /** * An API returns a job object like: * { id: 123, name: 'The Job ...

Sorts through nested arrays to uncover distinctive product assortments

Currently, I am in the process of developing a website using Next.js and Shopify. My objective is to create a page that displays all collections matching a specific productType. To achieve this, I have been exploring ways to extract this data from the Gra ...

NextJS: Retrieve the information in its initial state

Is there a way to retrieve the original format of a value? For example: The values in my textarea are: Name: Your Name Email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f980968c8b9c94989095b994989095d79a9694">[email ...

Instructions for including dependencies from a globally installed npm package into a local package

I've noticed that although I have installed a few npm packages globally, none of them are showing up in any of my package.json files. What is the recommended npm command to automatically add these dependencies to all of my package.json files? ...

Top Method for Initiating AJAX Request on WebForms Page

Looking for the best way to execute an AJAX call in a WebForms application? While ASP.NET AJAX components are an option, some may find them a bit heavy compared to the cleaner approach in MVC. Page Methods can be used, but they require static methods ...

Switch the URL of the current tab to a different one by clicking a button within a Chrome extension with the help of JavaScript

Could someone assist me in changing the current tab URL to a different website, such as , using a chrome extension? Here is my JavaScript code: chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { var tab = tabs[0]; console.log(tab.url) ...

What is the best way to create three buttons for selecting various parameters?

I have a code snippet where I want to assign different parameters to each button when clicked. However, despite my logic, the functionality is not working as expected. Can someone help me with the correct syntax? For example, if I click the "Start (Easy) ...

When PHP is connected to the database, Ajax remains inactive and does not perform any tasks

I am currently working on setting up a simple connection between JavaScript and my database using ajax and PHP. The goal is for JavaScript to receive a name from an HTML form, make changes to it, send it to PHP to check if the name already exists in the da ...

Error: The function gethostname has not been declared

I attempted to set a variable using gethostname() (1) and with $_SERVER(2), but I always receive an error message saying ReferenceError: gethostname is not defined. My goal is simply to fetch the current system name into a variable using JavaScript within ...

Flickering transitions in Phonegap and jQuery Mobile pages

As a beginner in Phonegap/jQuery Mobile, I have encountered a frustrating issue of a white screen appearing during page transitions. Despite trying various solutions found online, such as using -webkit-backface-visibility:hidden;, the problem persists. I ...

Display Google Maps and YouTube videos once user consents to cookies

I recently installed a plugin on my WordPress site called Cookie Notice, which I found at this link. So far, I've been impressed with how user-friendly and lightweight it is. Due to the latest GDPR regulations, I now need to figure out a way to hide ...

I'm curious if it's possible to modify a webpage loaded by HtmlUnit prior to the execution of any javascript code

To begin, I want to elaborate on the reasoning behind my question. My current task involves testing a complex web page using Selenium + HtmlUnit, which triggers various JavaScript scripts. This issue is likely a common one. One specific problem I encount ...

Struggling to update the color of my SpeedDial component in MUI

I'm having trouble changing the color of my speed dial button. The makeStyle function has been working fine for everything else. Any suggestions? import React, {useContext} from 'react'; import {AppBar, Box, Button, Container, makeStyles, To ...