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

Tips for adjusting column sizes in react-mui's DataGrid based on screen size

I would like the title column to occupy 3/4 of the full row width and the amount column to take up 1/4 of the full row width on all screens sizes (md, sx...). Here is the updated code snippet: import React from 'react' const MyComponent = () =&g ...

Is it possible to utilize ember-cli solely as a frontend tool, much like how we use JavaScript and jQuery?

Is it feasible to employ ember-cli exclusively as a front-end tool, similar to utilizing JavaScript and jQuery? I am interested in incorporating a reference to ember-cli in my .NET project solely for validation purposes. Is this a viable approach, and an ...

Toggle the on and off functionality of a button using ajax response for content display

I'm struggling to figure out why the button isn't working for me. I am familiar with how to enable and disable buttons using attr and prop. $(document).on("click", "#btn", function(){ $(this).html("Sending..."); $(this).prop("disabl ...

Sending the method's URL in the controller through an AJAX call

Below is the code snippet for an ajax call: <script> jQuery(document).ready(function() { $("#VEGAS").submit(function(){ var form_data = $("#VEGAS").serialize(); var routeUrl = "<?= url('/'); ?> /PUBLIC/vpage"; $.ajax({ ...

Having trouble combining different styles with Material-ui and Radium?

Trying to integrate Radium with Material-ui has presented a challenge. Attempting to apply multiple styles to a single Material-ui component results in no styling being applied. For instance, the following code fails to render any styling: <MenuItem st ...

Testing a Vuetify Data Table using Jest for unit testing

I've developed a Vue.js application utilizing Vuetify and I'm currently working on unit testing a component that contains a Vuetify Data Table. The issue arises when trying to populate the table in my unit test, where Axios is mocked with Jest. ...

Using Computed Values in Vue.js for Asynchronous Calls

I am working on setting up a dynamic array within the computed: section of my .vue file. This array consists of a list of URLs that I need to call individually (within a repeated component) in order to fetch articles. These articles can vary, so the comput ...

What is the best method for asynchronously injecting and providing data?

Within my page, I have implemented an asynchronous fetch method to initialize data: async fetch() { const res = await requestApi(this, '/database'); this.sliderData = res.homeSlider; this.modelData = res.model; ... } To pass thi ...

Getting Anchor Javascript to Submit in Internet Explorer. Functioning in Firefox, Chrome, and Safari

Greetings Stackoverflow enthusiasts, I have been working on a raffle form where users can input their name and select their location from a dropdown list. After filling out the form, they can click submit and their information will be stored in a database ...

Is there a way to select and handle multiple elements using async wdio with the same selector?

My test scenario involves using async wdio to test my React app, where I need to count elements with a specific selector and check their contents. The code snippet being tested is as follows: <div className='container'> <li className= ...

Webpack Error: SyntaxError - an unexpected token found =>

After transferring my project to a new machine, I encountered an error when running webpack --watch: C:\Users\joe_coolish\AppData\Roaming\npm\node_modules\webpack\bin\webpack.js:186 outputOption ...

Is the URL incorrect if fetching from Firestore URL results in a 404 error?

My current project involves fetching data from my Firestore Database using Next.js. However, I keep encountering an error in the console that reads GET (FirestoreDatabaseURL) 404 (not found). Interestingly, when I attempt to fetch data from other JSON dat ...

Issues arise with Highcharts Sankey chart failing to display all data when the font size for the series is increased

I am currently working with a simple sankey chart in Highcharts. Everything is functioning correctly with the sample data I have implemented, except for one issue - when I increase the font size of the data labels, not all the data is displayed. The info ...

Retrieve the input field value using JavaScript within a PHP iteration loop

I've implemented an input box inside a while loop to display items from the database as IDs like 001,002,003,004,005 and so on. Each input box is accompanied by a button beneath it. My Desired Outcome 1) Upon clicking a button, I expect JavaScript t ...

Plot the components of an array and calculate the instances that JavaScript executes

I have an array containing information about PDF files stored in a buffer. Let's imagine this array holds ten PDF files structured like this: [{ correlative: "G-22-1-06", content: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 d3 eb e9 e1 0a ...

I am encountering errors when running NPM start

After setting up my webpack, I encountered an error in the terminal when attempting to run the code npm start. The specific error message was related to a module not being found. Can someone please assist me with resolving this issue? > <a href="/c ...

Creating JavaScript objects through function calls

let getBoxWidth = function() { this.width=2; }; alert(getBoxWidth.width); Hello there! Can you explain why the output is undefined in this scenario? ...

A guide on setting up a countdown timer in Angular 4 for a daily recurring event with the help of Rxjs Observable and the Async Pipe

I'm currently working on developing a countdown timer for a daily recurring event using Angular 4, RxJS Observables, and the Async Pipe feature. Let's take a look at my component implementation: interface Time { hours: number; minutes: numbe ...

Guide on how to automatically direct users to a page upon successful login in ReactJS

How can I redirect to the homepage after a successful login in ReactJS? Also, how can I display an error message when a user enters incorrect credentials? I have attempted the following code, but it does not successfully redirect to the homepage or show ...

The Vue Multiselect component fails to properly update the {{ value }} when using v-model

I am currently implementing Vue Multiselect "^2.0.0-beta.14" within Laravel 5.3. You can find the example at https://github.com/monterail/vue-multiselect/tree/2.0#install--basic-usage The plugin is rendering properly, but I am facing issues in updating th ...