After refreshing the page, vuex is encountering null values when using firebase.auth().onAuthStateChanged

Encountering an issue with Vuex and Firebase Authentication integration. When reloading the page, there is a delay in response from firebase.auth().onAuthStateChanged. I require an immediate response upon page reload without using router guards as seen in most tutorials online. Some routes only allow access to logged-in users.

Implementing this in App.vue:

created () {
    firebase.auth().onAuthStateChanged(async user =>{
        if (user){
          await this.$store.dispatch('autoSignIn',user)
        }
      })
  }

The vuex action triggered for auto sign-in upon page reload:

 autoSignIn ({commit}, payload) {
            commit('setUser',{email:payload.email, userId:payload.uid})

        }

Getter used:

 isAuthenticated:state => {
    return state.user !== null && state.user !== undefined ? state.user : null
 }

Implementation of isAuthenticated getter:

  getEventsByUser({getters,commit}){

            let data = [];

            firebase.database().ref('usuario/' + getters.isAuthenticated.userId + '/eventos/')
                .on("value", eventos =>{
                     eventos.forEach(evento =>{
                        data.push({"id": evento.key, ...evento.val()})
                    });
                    commit('setEventsByUser',data)
                })

        },

The component dispatching the action:

<template>
    <div>
        <div v-for="(event,id) in getEventsByUser" :key="id">
            {{event}}
        </div>
    </div>
</template>

<script>
    export default {
        name: "MyEvents",

        computed:{
            getEventsByUser(){
                return  this.$store.getters.getEventsByUser;
            },
        },
        mounted() {
            this.$store.dispatch('getEventsByUser')
        },



    }

Error encountered upon reloading the page: https://i.stack.imgur.com/lU2hx.png

Answer №1

Upon loading the page, Firebase conducts a validation check to verify the current status of the stored user ID token. This process involves communication with the server, which may cause a slight delay. Throughout this verification, the user object will be null, necessitating careful handling in your code.

Your onAuthStateChanged handler effectively addresses this scenario by:

firebase.auth().onAuthStateChanged(async user =>{
    if (user){

However, within the getEventsByUser function, there is an assumption of the presence of a user, leading to the error message indicating otherwise. To rectify this issue, it is essential to include a conditional check to ensure the existence of a user before proceeding with attaching the listener to the database:

getEventsByUser({getters,commit}){
    let data = [];
    if (getters.isAuthenticated) {
        firebase.database().ref('usuario/' + getters.isAuthenticated.userId + '/eventos/')
        ...

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

Having difficulty creating the probot.github app due to an error: The removal of the programmatic API in npm version 8.0.0 causing failure

Currently, I am facing an issue while attempting to set up the probot.github app using the command npx create-probot-app my-first-app which can be found at: . My system is running on the latest node version v19.3.0 with npm version 9.2.0. However, upon exe ...

Using AJAX POST requests with PHP and SQL queries seems to function properly but unfortunately, it only

I am facing an issue with deleting an item from a list using AJAX, PHP, and MySQL. The first time I try to delete an item, the AJAX request works perfectly. However, on subsequent attempts, although the AJAX request returns success, the item is not deleted ...

How can you conceal an HTML element when the user is using an iOS device?

I need the code to determine if a user is using an iOS device and, if not, hide the HTML input type "Play" button. So, I'm uncertain whether my iOS detection is correct, the hiding of the "Play" button in the code, or both: <!DOCTYPE html> < ...

Using JavaScript, create a set of buttons within a div element and implement

$(document).ready(function() { $('#b1').click(function() { $('#uch').toggle("slow"); }); $('#b2').click(function() { $('#uch2').toggle("slow"); }) }) Although I'm not a program ...

Troubleshooting Problem with jQuery Function Call in Drupal 7

Encountering a particular issue in Drupal, though it may not be exclusively related to Drupal. This is the simple javascript code I am working with: (function ($) { function testing(){ alert('TEST function responding!'); } })(jQuery); ...

Display Image After Uploading with AJAX

After spending nearly 3 hours working on implementing file uploads via AJAX, I have finally managed to get it up and running smoothly. Take a look at the code below: View <div class="form-horizontal"> <div class="form-group"> @Htm ...

Matter of Representing Nested For Loops in Javascript Arrays

When I have two arrays that intersect at certain elements, the resulting function should ideally output A, B, Y. However, in this case, it displays all possible combinations of lista.length * listb.length. <script> window.onload = function(){ ...

Switch between two tabs with the convenient toggle button

I have implemented 2 tabs using Bootstrap as shown below: <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#home" role="tab" data-toggle="tab">CLient</a></li> <li role="presentatio ...

Does the current protected route that I am on restrict the user from navigating back to the Home component?

I'm having trouble figuring out how to redirect the user to the Home component when they logout. The API is functioning correctly based on my tests. However, I am unsure of how to implement the logout method in the current context to successfully log ...

Tips on utilizing controllers within AngularJs directives?

In order to utilize a controller in my directive, what is the best way to access all controller functions within the directive? directive.js angular.module('App').directive('deleteButtons', function (prcDeleteFactory,$rootScope) { & ...

Trouble arises when managing click events within the Material UI Menu component

I've implemented the Menu Component from Material UI as shown below - <Menu open={open} id={id} onClose={handleClose} onClick={handleClick} anchorEl={anchorEl} transformOrigin={{ horizontal: transformOriginRight, vertical: t ...

Node.js accepts JSON data sent via XMLHttpRequest

I have successfully implemented a post method using xmlhttprequest: var xhttp = new XMLHttpRequest() xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { console.log('Request finished. Pro ...

Unable to retrieve the value from a textarea when using Shopify Product Options by Bold

I'm currently facing an issue trying to retrieve the value of a textarea using Shopify's Product Options by Bold. The code works fine locally, but when I transfer it over to Shopify, I am unable to get the value. Despite looking at various resour ...

Can you explain how to invoke a class with express().use function?

Currently, I am delving into learning Node JS with TypeScript but have hit a roadblock with a particular issue. In my app.ts file, I have initialized the express and attempted to call the router class inside the app.use() method, only to encounter an error ...

Displaying postcode on a category page: A step-by-step guide

I would like to showcase the user input code and present it on the web exactly as entered. <?php #code... ?> Any assistance is greatly appreciated. Please excuse my English. Thank you! ...

Guide to generating a PDF file and utilizing a Node.js program for the download process

Seeking assistance in creating a button using my Node.js application to generate a downloadable PDF file filled with information from a PostgreSQL database. Any help is greatly appreciated! ...

The error "500 window is not defined in Nuxt3 when using the composition API"

Is it possible to detect the user's preference for color scheme and set a data-mode attribute on the document root (html)? I've been struggling with this. In my app.vue code, I have the following: <template> <div> <NuxtLayout /> ...

Creating one div to initiate the contents to fadeToggle and another div to cease the fadeToggle animation utilizing the setInterval function in JavaScript

Here is the link to my Fiddle: http://jsfiddle.net/tmanundercover/62ap2/ CSS #targetedDiv, #otherDiv { border: 1px solid; } HTML <div id="targetedDiv">&nbsp<span id="fakeCursor">|</span></div> <br> <div id="othe ...

Experiencing problems with npm and bower installations, along with deprecated modules while setting up angular-phonecat project

Trying to execute npm install in terminal while setting up angular-phonecat based on instructions from https://docs.angularjs.org/tutorial Encountering issues with deprecated modules and errors during the bower install phase. Seeking advice on how to upd ...

Challenge with neglected open connections from a comet

Utilizing various comet techniques like long polling and forever frame, along with iframes for cross subdomain activities, has presented a challenge during implementation. When a user refreshes the page or navigates to another page, a new request is made w ...