Accessing data in vuex can result in Firebase SnapShot.val() returning null

I am developing an application that allows access for students, staff, and non-teaching staff.

Here is how my form data is structured:

formData: {
      name: "",
      email: "",
      password: "",
      select: null
    },
    options: ["Student", "Staff", "Non-Teaching Staff"],

When it comes to registering users in Vuex store, I use the following method:

registerUsers({}, payload) {
    firebaseAuth.createUserWithEmailAndPassword(payload.email, payload.password)
      .then(res => {
        const userId = firebaseAuth.currentUser.uid;
        console.log(res)
        Notify.create({
          message: 'Registration Successful!',
          color: 'primary',
          classes: 'quick'
        })
        //set user role
        firebaseDb.ref(`users/'${userId}`).set({
          name: payload.name,
          email: payload.email,
          select: payload.select
        });
      })
      .catch(err => {
        console.log(err)
        Notify.create({
          message: `${err.message}`,
          classes: 'quick',
          color: 'negative'
        })
      })

For logging in users, I have implemented the following method:

loginUsers({}, payload) {
    firebaseAuth.signInWithEmailAndPassword(payload.email, payload.password)
      .then(res => {
        console.log(res);
        Notify.create({
          message: 'Success!',
          classes: 'quick',
          color: 'positive'
        })
      })
      .catch(err => {
        console.log();
        Notify.create({
          message: `${err.message}`,
          classes: 'quick',
          color: 'negative'
        })
      })
  },

The problem arises with this piece of code:

handleAuthStateChange() {
    firebaseAuth.onAuthStateChanged(user => {
      if (user) {
        //set user role
        const userId = firebaseAuth.currentUser.uid;
        console.log(userId)
        firebaseDb.ref(`users/${userId}`).once('value', snapshot => {
          console.log(snapshot.val())
        })
      }
    })
  },

The `snapshot.val()` is returning null in the console output.

Please help me identify what I might be doing wrong here.

Answer №1

When you use

firebaseDb.ref(`users/'${userId}`).set({...})
, you are inadvertently creating your user under a node

users/'userId

with an unnecessary single quote (').

You may have intended to read from the node

users/userId

which does not actually exist if there is a typo with the single quote.


Furthermore, it’s important to mention that there is no need for

firebaseAuth.createUserWithEmailAndPassword(payload.email, payload.password)
  .then(res => {
    const userId = firebaseAuth.currentUser.uid;
    //...

because createUserWithEmailAndPassword() returns a UserCredential. You can simply do:

firebaseAuth.createUserWithEmailAndPassword(payload.email, payload.password)
  .then(res => {
    const userId = res.user.uid;
    //...

Additionally, remember that you can utilize:

handleAuthStateChange() {
    firebaseAuth.onAuthStateChanged(user => {
      if (user) {
        const studentId = user.uid;
        //......

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

Uncovering the websocket URL with NestJS and conducting postman tests: A step-by-step guide

Creating a mean stack application using NestJS involves utilizing websockets. However, testing websockets in Postman can be confusing. Typically, I test route URLs in Postman and get output like: "http://localhost:3000/{routeUrl}". But when it comes to tes ...

Can an array be used as valid JSON for a REST api?

Utilizing MongoDB with Mongoskin in a web application using Node.js allows for the execution of .find() on a collection to retrieve all documents within it. The result returned is a mongodb cursor. To convert this cursor into an Array, you can utilize the ...

Switching a Rails/Ajax form from create to update mode upon submission

While experimenting with a star ratings page, I encountered an issue where the form element remained in "Create" mode instead of updating to an "Update" method after submission. The rating form is ajaxified, but it lacks the functionality to dynamically sw ...

How can I create a cube with complete beveling using Three.js?

I'm struggling to create a beveled cube in my project. I have come across the THREE.ExtrudeGeometry snippet in the documentation here. However, when I tried it out, I only managed to achieve beveled sides on the top and bottom faces like this: https: ...

How can multiple arguments be passed to a function using JQuery's post method?

I can't seem to figure out how to pass multiple arguments to a function using jQuery's post method. It might sound like a silly question, but I'm struggling with it. Currently, my code looks something like this: $.post("<?php echo site_ ...

What does {``} denote in react-native programming?

During my participation in a collaborative project, I noticed that there is a significant amount of {' '} being used. For instance: <Text> {' '} {constant.Messages.PointText.hey} {this._user.first_name || this._user ...

Is it possible to run vue-cli-service serve at a different directory for testing reasons?

Whenever I start vue-cli-service serve on my development machine for testing, it automatically hosts my project at the root URL (i.e. "/"). I am interested in launching vue-cli-service serve at a non-root path (i.e. "/test/") so that ...

What is the best way to deselect the first radio button while selecting the second one, and vice versa, when there are two separate radio groups?

I am looking to achieve a functionality where if the first radio button is selected, I should receive the value true and the second radio button should be unselected with the value false. Similarly, if the second radio button is selected, I should receive ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...

Issues with Callbacks Inquiry

I'm struggling to understand how to implement callbacks in this scenario. Despite researching and reading explanations, I can't seem to grasp the concept. Below is a snippet of my code: function retrieveTransactionInfo(transactionUrl) { re ...

What could be causing the mousewheel event in my code to remain active?

Whenever I try to scroll on Google Chrome, an error occurs on my website. jquery-3.3.1.min.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See To resolve this issue: $(document).ready(f ...

Node.js encountering unexpected pattern during RegExp match

Currently, I'm developing a script that aims to simplify local testing by creating a Node server for all my Lambda functions. My main challenge lies in extracting all the dbconfig objects from each file. To test out various patterns, I rely on . Surpr ...

Issue with Angular 6 subscribe event not being caught by subject?

A new element was crafted to house a loader: @Component({ selector: 'app-loader', templateUrl: './loader.component.html', styleUrls: ['./loader.component.scss'], providers: [LoaderService] }) export class LoaderCompon ...

Leveraging jQuery in Content Scripts for Chrome Extensions

I am currently working on developing a Chrome extension that will prompt a small input whenever a user highlights text on a webpage (similar to Medium's feature that allows you to tweet highlighted text). While I am making progress, I believe using j ...

Exploring deeply nested objects within Express by iterating through them

I am trying to figure out how to iterate through objects in Express.js. I can retrieve information from the JSON file, but when I attempt to loop through it, I keep getting an error saying that it's not defined. What could I be missing here? My goal ...

Leveraging async/await within a React functional component

Just getting started with React for a new project and facing challenges incorporating async/await functionality into one of my components. I've created an asynchronous function called fetchKey to retrieve an access key from an API served via AWS API ...

The Dropdown Button Functions Once and Then Stops

I am facing a challenge in implementing a button within an HTML table that triggers a dropdown menu when clicked, and closes upon another click or when the user clicks outside the menu. Oddly, the button only seems to work once before completely losing fun ...

Unable to add items to the global JavaScript array variable

My goal is to populate a global array variable within my ready function, but when I attempt to access the data later on, the array appears to be empty. This is how my ready function looks: var counter = 0; var services = []; var names = [] va ...

Verification of javascript for an unpredictable image generator script

When running the W3C Validation tool, an error is returned stating 'img not acceptable here.' Any suggestions on how to resolve this issue? <script type="text/javascript" language="JavaScript"> NumberOfImagesToRotate = 9; FirstPart = &ap ...

How can I retrieve information from a topic using kafka-node?

Having trouble reading data from a Kafka server? You may encounter an error message stating that the topic does not exist. Here are some questions to guide you: 1- How can I ensure that my Kafka connection is established? 2- What is the process for retri ...