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

Concealment Based on Surroundings

I'm currently working on implementing a new feature called 'context-based hiding' which involves hiding content based on mouse actions. I've been struggling to figure out how to create this feature and came across a website that has it ...

Preventing multiple tabs in a form with PHP

I have successfully used JavaScript to prevent a link from being opened in multiple browser tabs every time a user clicks on it. For example, if the destination of my link is Google, it will create a new tab if one does not already exist but refresh the ex ...

Utilizing Webpack's tree shaking functionality with the Vue template's v-if directive: a step-by-step guide

[email protected] [email protected] <template> <module-x v-if="isClientX"></module-x> <module-y v-else></module-y> </template> <script> export default { computed: { isClientX() { ...

The IISNode website displays directory contents instead of launching the server.js file

Having trouble configuring IISNode to automatically serve the main server.js application file for my node application. Currently, when I navigate to http://localhost:80/ where my app is hosted, it just displays the folder contents instead of running the se ...

"Exploring the Wonders of Regular Expressions in JavaScript: Embracing the Truth and All

Hey there! I've been working on a JavaScript script to test password field validation. As of now, I have successfully made the script display an alert when the requirements are not met. However, I am now facing an issue regarding what action to take o ...

exploring the contrast of css versus javascript selectors

Could you please explain the contrast between div#name and #name? Is there a significant difference when using class or id to position an element? Thank you for your help. ...

Tips for Removing Padding in Material UI Container Component

I'm currently working on creating a hero banner using the material-ui framework and I've encountered an issue. Here's what I have so far: https://i.stack.imgur.com/UXTDY.png However, I'm facing an irritating problem with left and rig ...

What is the best way to ensure only one item is being selected at a time?

In the initial state, I want 'ALL' to be automatically selected. Clicking on another item should change the classes so that only 'this' has the class and the others do not. However, I am facing an issue where 'ALL' cannot be r ...

How can you use HTML, CSS, and JavaScript to group objects with one color and then change the color of one specific object?

I have a set of 6 labels that act as buttons. When one is clicked, it changes from white to blue. If another label is clicked, the previously blue label turns white and the newly clicked one turns blue. Currently, the code below sets all labels to white b ...

Creating dynamic components in Vue.js

I am currently developing a chat application using Vue. In this application, when one user (User A) wants to send an image to another user (User B), the image is uploaded to the server and the name along with the URL of the file is returned. My main query ...

"Error: The $ variable is not defined" - encountered while working with a date-time picker in Jade/Pug

I am attempting to implement a date/time picker in jade/pug that resembles the example provided on this page: . I am working with a Node/express js server. However, when I click on the glyphicon-calendar icon, the calendar fails to display. I have already ...

Utilizing AJAX in Wordpress to Dynamically Update HREF Links

My website now has AJAX functionality, and you can see a live example at www.mathewhood.com. I am interested in changing the URL format when clicked from To something like , without the /sitefiles/ for security reasons. Below is my code. If anyone is ex ...

The fade-in effect will initiate from the start once the mouse leaves the element (with a

Currently, I am in search of a solution for improving the navigation menu I am developing. By clicking on this JSFiddle link, you can view the code in action. The issue I am facing is that the fadeIn effect should only occur when hovering over the nav-ite ...

Customizing Tabs in Material UI v5 - Give your Tabs a unique look

I am attempting to customize the MuiTabs style by targeting the flexContainer element (.MuiTabs-flexContainer). Could someone please clarify the significance of these ".css-heg063" prefixes in front of the selector? I never noticed them before upgrading my ...

Exploring the boundaries of React's useContext functionality

In my applications, I specialize in creating custom hooks for accessing state stores. For example, I typically define the hook like this: const store = new Store(); const StoreContext = createContext(store); StoreContext.displayName = "StoreContext"; fun ...

What is the reason that the index is consistently the final index when utilizing it to pass to a function while iterating over an array with map()?

Currently, I am utilizing the map function to iterate over an array object fetched from the server. Each object within the array is used to populate a row in a table for displaying data. I need to perform a specific action for each row by invoking a functi ...

What steps can be taken to align the description in the center of the div?

I am working on an image slider where the description slides in from left to right. My goal is to align the text justified and center it on the page. However, when I try adding CSS properties, it doesn't seem to have any effect. setting.$descpanel=$( ...

Updating the button text in Angular 7

Here's a question: <button (click)="activateMotion(1)"> <img class="emotion-icon" id="positive-icon" src="" /> </button> <button (click)="activateMotion(-1)"> <img class="emotion-icon" id="negative-icon" src="" /&g ...

NestJS: Specify the data type for @Body()

Consider the code snippet below: @Post() public async createPet(@Body() petDetails: PostPetDto): Promise<any> { } In this scenario, the type of @Bod() petDetails defaults to plain/any instead of the declared type of PostPetDto. What is the recommen ...

Setting a variable equal to user input

When using a jQuery script, the elements for the details are dynamically created inside a jQuery function. However, there seems to be an issue with assigning the value from the variable "startLocation" to the input "detail_startLocation[]". Only the firs ...