Retrieving user email with Vue.js from Firebase

Currently, I am in the process of developing a chat application using Vue.js and Firebase.

This project has been quite challenging for me as I am new to both Vue and Firebase. One specific issue I have encountered is trying to retrieve the user's email in order to display it alongside the chat messages on Firebase. Despite attempting various solutions and seeking help from resources like Stack Overflow, I still haven't been able to make it work. The concept of accessing 'root' in my code seems to be causing some confusion, especially when I try methods like this.$root.something.

One example of my code can be found below in the main.js file:

firebase.auth().onAuthStateChanged(function(user) {
    if (!app) { 
        /* eslint-disable no-new */
        app = new Vue({
          el: '#app',
          data: {email: user.email}, //Storing the email here works but I struggle with accessing it from other components
          template: '<App/>',
          components: { App },
          router 
        })
    }
});

In my main component script, I'm aiming to access the root:

<script>
    import * as firebase from 'firebase'

    export default {
        name: 'chat',
        data: function(){
            return {
                room: null,
                db: null, //Firebase SDK assignment later
                messageInput:'', //For v-model
                messages: [],
            }
        },
        mounted() {
            this.db = firebase
            // Accessing the location and initializing a Firebase reference
            this.init()
        },
        methods: {
            init(){
                this.room = this.db.database().ref().child('chatroom/1')
                this.messageListener()
                this.saveEmail();
            },
            saveEmail(){
//Attempting to save the email using the onAuthStateChanged method
                firebase.auth().onAuthStateChanged(function(user) {
                    this.$root.email = user.email;
                });
            },
            send(messageInput) {
                let data = {
                    message: messageInput
                };
                let key = this.room.push().key;
                this.room.child('messages/' + key).set(data)
                this.messageInput = ''
            },

            messageListener () {      
                this.room.child('messages').on('child_added', (snapshot) => {
                    this.messages.push(snapshot.val())
                })
            },
            logout(){
                firebase.auth().signOut().then(() => {
                    this.$root.email = null;
                    this.$router.replace('login');
                })
            },  
        }
    }
</script>

The script in my login component:

<script>

    import firebase from 'firebase'

    export default {
        name: 'login',
        data: function(){
            return {
                email: '',
                password: '',
            }
        },
        methods: {
            signIn: function(){
                firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(
                    (user) => {
                        this.$root.email = user.email;
                        this.$router.replace('chat');
                    },
                    (err) => {
                        alert('Oops! ' + err.message);
                    }
                );
            },
        }
    }

</script>

If my explanation is unclear, kindly let me know. Thank you for your assistance!

Answer №1

The callback function for the onAuthStateChanged method is incorrectly bound to a different this scope. To rectify this issue, you can simply utilize an arrow function as shown below. Arrow functions automatically maintain the context in which they are defined.

updateEmail() {
  firebase.auth().onAuthStateChanged((user) => {
    this.$root.email = user.email;
  })
}

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

Axios encounters a problem: Unable to access the property '$get' as it is undefined

Find the code on github: https://github.com/aurora10/amazone-clone.git Attempting to use Axios to communicate with an API is resulting in the following error: The console shows a NUXT SSR error: TypeError: Cannot read property '$get' of undefi ...

Create a wait function that utilizes the promise method

I need to wait for the constructor() function, which contains an asynchronous method handled by Promise. My goal is to wait for two asynchronous methods within the constructor, and then wait for the constructor itself. However, my code is throwing an err ...

Building a Vue application with Node.js, Express, and XAMPP requires careful consideration of the project

I'm looking to develop a CRUD application using technologies such as: - Vue.js - Node & Express - mysqli (xampp) What would be the most effective approach to structuring the project's directory and files tree? Is it preferable to separate into t ...

You can only use the angularjs http function once

After browsing through similar forum posts, I was unable to find a solution to my issue. It could be due to my limited experience with JavaScript and Angular. Here's the problem: Desired Outcome: When I click a button, I want the data from the server ...

Converting an HTMLElement to a Node in Typescript

Is there a method to transform an HTMLElement into a Node element? As indicated in this response (), an Element is one specific type of node... However, I am unable to locate a process for conversion. I specifically require a Node element in order to inp ...

Integrating Gesture Handling in Leaflet JS for two-finger scrolling enforcement

Have you ever noticed that when you're using a mobile device and scrolling down a webpage with a Google map, the map goes dark and prompts you to "Use two fingers to move the map"? https://i.stack.imgur.com/4HD1M.jpg I am interested in incorporating ...

Using the v-for directive to create sequential lists

I am struggling to display pairs of data from an object based on category using nested v-for loops. The object, categoryArray, contains entries such as {stage 1, red}, {stage 1, blue}, {stage 2, orange}, {stage 3, brown}, {stage 2, green. My desired displ ...

Transform a log file into a JSON structure

In my log file titled request.log, the following entries are present: [2022-06-30T09:56:40.146Z] ### POST https://test.csdf/auth/send_otp { "method": "POST", "headers": { "User-Agent": "testing&q ...

Compilation failure resulting from core UI build in React js

I have recently transitioned my domain to React Js and am in the process of learning. I have been working on creating an admin panel using Core UI Reactjs components, however I keep encountering an error that says "This error occurred during the build ti ...

Performing an Ajax request using MooTools when my button is clicked

After clicking a button, I want to initiate an ajax call. There are more than 14 buttons on my site that make ajax requests to fetch elements from various parts of the site. Button, Button1, Button2, Button3 | | | load content | | ...

JavaScript isn't functioning properly after UserControl is loaded via Ajax

Thank you, Stilgar for helping me solve my issue. I created a javascript file and placed all my code in it. After adding this file to the UserControl and retrieving the UserControl's html, I used $("#DivID").html(UserControlHTML). Now everything is wo ...

Leveraging jQuery for handling button functionality and making asynchronous requests

I am relatively new to working with jQuery, and while there are plenty of resources available on how to bind buttons, I find that my current setup is a bit more complex than what's typically covered. My situation involves: -Using Django to populate ...

The Dropdownlist jQuery is having trouble retrieving the database value

Within my database, there is a column labeled Sequence that contains integer values. For the edit function in my application, I need to display this selected number within a jQuery dropdown list. When making an AJAX call, I provide the ProductId parameter ...

Ways to stop your Browser from Caching

Developing a Facebook app has been my recent project. One thing that really bothers me is the random occurrences where changes I make to my CSS style sheet or when adding a new Javascript function do not reflect in the browser. This can be very frustrating ...

Mapping Vue routes to perform redirects

Looking for a quick solution here. Here is the mapping I am working with: const routes = routeOptions.map((route) => { return { children: route?.children?.map((child) => { return { ...{ path: child.path, name: ...

Sending Parsed Information to Callback for Flexible Use

Is there a way to pass the value of coins, or even better, currency to my callback function so I can freely use the parsed JSON data in other functions? function fetchJSON(path, callback) { var jsonReq = new XMLHttpRequest(); jsonReq.onreadystatechang ...

Managing errors and error codes in React/Redux applications

I am currently exploring the most effective approach for managing errors, particularly when deciding between error codes and an errors object in response from my API. As I dive into building a multi-part form using react, each time a user progresses to th ...

Unexpected behavior: Controller action method retrieves undefined value upon jQuery Ajax request

I'm currently working on my ASP.NET Core 3.1 project and implementing cascading dropdown functionality with jQuery. I've set it up so that changing the value of the first dropdown (Region) should automatically update the second dropdown, Location ...

What is the best way to direct users to the individual product page once they make a selection

On my main products page, I am fetching all the products from a local JSON file. interface productItem { id: number; name: string; image: string; price?: string; prices: { half: string; full: string; }; ...

Creating a dynamic JSTree that loads data on demand using Stored Procedures

Currently in my SQL Server database, I have two Stored Procedures that are responsible for extracting data from a tree structure: One procedure retrieves all nodes at a specific level based on the provided level number. The other procedure retrieves th ...