What could be the reason for parent props not updating in child components in VueJS?

Hello, I am new to VueJS and encountering an issue.

In the main.js file, I am passing the user variable to App.vue using props. Initially, its value is {}

The getLoginStatus() method in main.js monitors the firebase authentication status, and when a user logs in or out, main.js.this.user gets updated.

Although user in main.js is transferred to App.vue through template, any changes due to the getLoginStatus() function are not reflected in App.vue (the child component), unlike in main.js where it does get updated.

Do you have any suggestions on how to resolve this?

Here is my main.js code:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import firebase from "firebase";
Vue.config.productionTip = false

var firebaseConfig = {
    CONFIGURATION
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();

new Vue({
    el: '#app',
    router,
    template: '<App :user="user" ></App>',
    components: { App },

    data(){
        return {
            user : {}
        }
    },
    methods:{
        getLoginStatus(){
            firebase.auth().onAuthStateChanged(function(u) {
                if (u) {
                    this.user = u
                    console.log("// User is signed in by Phone Number : ", u.phoneNumber)

                } else {
                    this.user = null
                    console.log("// No user is signed in.")
                }
            });
            console.log("this.user new value : "+this.user);
        },
    },
    updated(){
        this.getLoginStatus()
    },
    created(){
        this.getLoginStatus()
    }
})

And here is my App.vue code:

<template>
    <div id="app">
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <a class="navbar-brand" href="#">Navbar</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <router-link class="nav-link" to="/">Home</router-link>
                    </li>
                    <li class="nav-item">
                        <router-link class="nav-link" to="/register">Register/About old</router-link>
                    </li>
                    <li class="nav-item">
                        <router-link class="nav-link" to="/dashboard">Dashboard</router-link>
                    </li>
                    <li class="nav-item">
                        <button class="nav-link btn" @click="logout">Logout</button>
                    </li>
                </ul>
            </div>
        </nav>
        <div class="container mt-5">
            <router-view />
        </div>
        <p v-if="user">logged{{user}}</p>
        <p v-else>not logged{{user}}</p>

    </div>
</template>

<script>
    import firebase from 'firebase'
    export default {
        name: 'app',
        props: ['user'],
        methods:{
            logout() {
                firebase
                    .auth()
                    .signOut()
                    .then(() => {
                        alert('Successfully logged out');
                        if(this.$router.currentRoute.path!='/'){
                            this.$router.push('/')
                        }
                    })
                    .catch(error => {
                        alert(error.message);
                        if(this.$router.currentRoute.path!='/'){
                            this.$router.push('/')
                        }
                    });
            },
        },
    }
</script>

Answer №1

It appears you have encountered an unbound function in your code:

firebase.auth().onAuthStateChanged(function(u) {

When you try to set this.user within this function, the reference of this is not directly pointing to your Vue instance. To resolve this issue, you can either use .bind(this) on your function or switch to an arrow function which automatically binds:

firebase.auth().onAuthStateChanged(u => {

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

Display the current language in the Vue language dropdown

My component is called DropdownLanguage.vue Goal: I need to show the current active language by default in the :text="selectedOptionDropdown" attribute. For example, it should display "English" which corresponds to languages.name. I'm struggling with ...

ReactiveJS - Adding elements to an array and encountering the error of undefined

In two separate JavaScript files, I have 2 arrays declared as shown below: Index.JS: const [product, setProduct] = useState([]); const [item] = useState([ { name: 'Blue Dress', Image: '/static/media/Dress.1c414114.png', Pr ...

Add an element to the parent body from an iframe with this easy tutorial!

Within the iframe, I have the following code snippet. <script type="text/javascript"> $(document).ready(function(){ $("body").append($("#ctap").html()); }); </script> I am looking to append the HTML content of #ctap to the par ...

Retrieving component attributes using jQuery or alternate event handlers

In my Angular2 component, I am facing an issue with using vis.js (or jQuery) click events. Despite successfully displaying my graph and catching click events, I encounter a problem where I lose access to my component's properties within the context of ...

Is utilizing the correct use case for a Bunyan child logger?

I've recently started exploring bunyan for logging in my nodejs application. After giving it a try, everything seems to be functioning quite smoothly. Initially, I overlooked a section on log.child, but now I am eager to understand its usage. It appea ...

Updating the textarea with Ajax without the need for a button click or refreshing the

I need to implement a feature where a textarea will automatically update the database without requiring the user to click on any buttons or refresh the page. The idea is that after a keyup event, there should be a 2-second countdown timer. If no additional ...

A common inquiry: how can one pinpoint a location within an irregular figure?

I have been studying Html5 Canvas for a few weeks now, and the challenge mentioned above has puzzled me for quite some time. An irregular shape could be a circle, rectangle, ellipse, polygon, or a path constructed by various lines and bezier curves... I ...

Using Jquery to duplicate a row from one table and insert it into another table

Recently, I've dived into the world of jQuery and JavaScript with the goal of creating a simple app. The main functionality I'm trying to implement is the ability to copy a row from one table to another and then delete the original row when a but ...

Error: The variable "message" has not been defined. Please define it before displaying the welcome

While I was experimenting with my welcome message and attempting to convert it into an embed, I ended up rewriting the entire code to make it compatible. However, upon completion, I encountered the error message is not defined. var welcomePath = './ ...

How to retrieve the button value in HTML

One of the HTML components I am working with is a button that looks like this: <button>Add to cart</button> My goal is to retrieve the text within the button, which in this case is "Add to cart." To achieve this, I need to extract this value ...

Text that is selected within a contenteditable div: Find the beginning and end points of the highlighted text

<div contenteditable="true">This text is <b>Bold</b> not <i>Italic</i> right?</div> For instance, if the text appears in a bold format, but not italic and the user selects it, how can I determine the exact position ...

Block users from viewing the image displayed within a JavaScript canvas

On my server, I have a path to an image that is accessed by a JavaScript to load the image onto a canvas. The script then proceeds to hide certain parts of the image using black layers. The issue arises when a user can easily view my JavaScript code, extr ...

Problems with Wordpress AJAX search functionality

I am currently working on implementing a search feature using AJAX to dynamically load posts. However, I am facing an issue where the results are not being displayed. This code snippet was adapted from another source and modified based on private feedback ...

Navigate through chosen options by clicking on a button

It's a new day and I'm facing a simple challenge that seems complicated in the morning haze. I need to create a select dropdown with zoom percentage values, along with + and - buttons to navigate through the list. If I have the following setup: ...

What is the reason for not using constants for events in the Node.js programming language?

Although I am new to node.js, my programming background is extensive. I have noticed that in tutorials and production code, developers tend to use hard-coded strings rather than constants to identify events. To illustrate this point, I randomly selected a ...

Canceling a window in JSP and navigating back to the previous page using JavaScript

Here is my Java class controller: public class Controller extends HttpServlet { private Chooser chooser = Chooser.INSTANCE; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOExcep ...

Problem with Material-UI Drawer

Is there a way to make this drawer stay fixed on the page like a sticker and remain active without moving when scrolling? I've tried using docked={false}, but it makes the whole page inactive except for the drawer. Any suggestions on how to solve this ...

Issue encountered with the @babel/plugin-proposal-private-property-in-object package persists despite successful installation

Every time I try to run my Nuxt app, an error pops up: Error: [BABEL] C:\Users\my.name\Projects\blabla_project\.nuxt\client.js: --- PLACEHOLDER PACKAGE --- The @babel/plugin-proposal-private-property-in-object version being i ...

Transferring form data from Jade to Node.js for submission

My Jade template includes the following form structure: form(action='/scheduler/save/' + project.Id, method='post') div.form-group label.control-label.col-md-2 RecurringPattern di ...

Tips for extracting header ID from the HTML/DOM using react and typescript

I developed a unique app that utilizes marked.js to convert markdown files into HTML and then showcases the converted content on a webpage. In the following code snippet, I go through text nodes to extract all raw text values that are displayed and store t ...