The issue of accessing the session before scripts are loaded arises when using VueJS alongside Firebase Authentication

Currently grappling with a project where I'm facing some challenges... I've opted for VueJS on the frontend and implemented Firebase Authentication for user login.

I'm trying to determine the login status of a user by using firebase.auth().currentUser; (If it returns null, then no user is logged in) Sounds straightforward, right?

In my VueJS created() function, when I run firebase.auth().currentUser;, it consistently returns null. It seems like Vue is attempting to retrieve the data before it's fully loaded.

Your patience and assistance are greatly appreciated - I'm fairly new to both Vue and firebase! Code snippets have been provided below.

    Vue.config.devtools = true;
    var app = new Vue({
        el: '#app',
        data: {
          user: '',
          loggedIn: false
        },

        created() {
              var user = firebase.auth().currentUser; 
              if (user != null){
                this.user = user;
                this.loggedIn = true;
              } else {
                this.loggedIn = false;
              }
        }
    })

Displayed below are the firebase scripts that are included at the bottom of the page body

<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-analytics.js"></script>
<script src="js/firebaseConfig.js" type="text/javascript"></script>

How can I rectify this issue without resorting to a setTimeout() method? Additionally, which script manages this session within Firebase?

Answer №1

firebase.auth().currentUser may initially return null upon page load, as it only holds a user object once the SDK confirms the user is signed in. The timeframe for this confirmation can vary.

To monitor this process, consider using an auth state observer outlined in the documentation.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    // ...
  } else {
    // User is signed out.
    // ...
  }
});

This callback is useful for determining when to display content specific to each user.

For further insights into Firebase Auth SDK behavior, check out this blog post.

Answer №2

async onInit() {
          let currentUser = await firebase.auth().getCurrentUser(); 
          if (currentUser !== null){
            this.currentUser = currentUser;
            this.isLoggedIn = true;
          } else {
            this.isLoggedIn = false;
          }
    }

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

How can I ensure that the HTML I retrieve with $http in Angular is displayed as actual HTML and not just plain text?

I've been struggling with this issue for quite some time. Essentially, I am using a $http.post method in Angular to send an email address and message to post.php. The post.php script then outputs text based on the result of the mail() function. Howev ...

Asynchronous and nested onSnapshot function in Firestore with await and async functionality

I'm facing an issue with the onSnapshot method. It seems to not await for the second onsnapshot call, resulting in an incorrect returned value. The users fetched in the second onsnapshot call are displayed later in the console log after the value has ...

Managing messaging broadcasts for messenger bots by creating and retrieving unique identifiers

As a beginner using a starter project from glitch, I have a project set up at this link: I need help understanding how to obtain the message_broadcast_id and how to create it. This is how I usually create a normal message: function callSendAPI(messageDa ...

When using Next.js and Express.js together, CORS error may occur, causing API queries to only function properly during build

I am currently working on a project that involves using Next.js for the front-end and Express.js for the back-end. Front-end Setup The 'pages' directory contains an 'index.js' file where I have implemented the following code snippet: ...

Tips for transferring the output of a JavaScript async function to a Python variable

var = driver.execute_script("setTimeout(function(){ return [1,2,3]; }, 1000);") Utilizing the Selenium method execute_script, I am attempting to extract data from a website using javascript and assign it to a python variable var. The challenge a ...

What are the steps to transform an object containing arrays into strings and then embed them into my HTML code?

Here is the code I need to add to my errors array and send the values to my HTML client-side template: { "email": [ "user with this email already exists." ] } I am looking for something like this: "user with t ...

Using Angular JS to submit forms on a regular basis

My HTML form is set up within an Angular controller with inputs, action, and other elements already defined. The only issue I'm facing is that the form does not have a traditional submit button. Instead, there is a separate button on the page outside ...

Updating SVG colors using VueJS

I'm struggling to change the color of an existing static SVG image. Here's the code I have: <img class="icon-shop" src="@/assets/icon-shop.svg"/> <style> .icon-shop { width: 32px; fill: orange; stroke: oran ...

The Forward and Back Buttons respond based on the current position of the caret

Exploring the concept of a Keypad-Login. I am trying to create Back and Forward buttons. However, the back and forward buttons are currently inserting the letters at the end of the input value instead of at the caret position. The input field is disabled, ...

What is the best way to enable ondemand icon usage in Vue Vite 3 with Iconify?

Did you know in the iconify documentation, there is just one simple step to follow? Visit All you have to do is: npm install --save-dev @iconify/vue import { Icon } from '@iconify/vue'; <Icon icon="mdi-light:home" /> After thi ...

Node.js and the concept of handling null values

console.log("variable = " + JSON.stringify(result.something)); After running the code, I see that variable = null However, when I add this condition: if (result.something != null || result.something != '') { console.log('entered' ...

beforeSend method in jquery ajax synchronously calling

One of my functions is called: function callAjax(url, data) { $.ajax( { url: url, // same domain data: data, cache: false, async: false, // use sync results beforeSend: function() { // show loading indicator }, ...

The HTML view is unable to display the CSS style due to a MIME-type error

I have recently developed a very simple Express app that is supposed to display a single view called home.html from the view directory. Although the home.html file is being shown, none of the CSS styles I added seem to be loading. The console is throwing t ...

Transitioning from a multipage application to Piral: A comprehensive guide

Our organization operates several ASP.NET Core applications that are traditional multipage applications. As we develop a new portal using Piral, we want to incorporate elements from our existing applications while also introducing new modules. How can we ...

The incorrect date selection made by the Datepicker feature in the Vue / Buefy component

Currently, I am utilizing Vue / Buefy as a datepicker in the form on a specific page (2nd step). You can find the page here: An issue has arisen where the date of birth input is sometimes recorded inaccurately. For instance, the user selects June 5th, 197 ...

Exploring Date Comparisons in AngularJS

Currently, I am in the process of developing a web application using AngularJS and Rails. One of the features involves creating bookings through a bookings function. In the dashboard section of the app, I aim to have two tabs - one for Current Bookings and ...

Customize the color of the hamburger icon in Vue Bootstrap

I am struggling to change the color of the Vue Bootstrap Hamburger navbar-toggler-icon to white. Despite trying numerous code combinations, I have not been successful. Each time I load the app, the CSS defaults back to the original bootstrap URL. Do you ha ...

What is the issue with undefined params in Next.js?

I have come across an issue with the function in app/api/hello/[slug]/route.ts When I try to log the output, it keeps showing as undefined. Why is this happening? The code snippet from app/api/hello/[slug]/route.ts is shown below: export async function G ...

Trigger an alert when a button is clicked and redirect the user to an newly opened tab

I recently created a button with a link that opens in a new tab. I also implemented some JavaScript to display an alert. Everything is working as expected, but after the user clicks "OK" on the alert, they remain on the same page. I would like to automati ...

Exploring Vue 3 and Pinia: Achieving Reactivity in Stored Values

Currently, I am working on a project using Vue 3 with the Composition API and Pinia. Within my application, I have an auth store that retrieves the default email and password values from the store. import { useAuthStore } from "stores/auth"; const authSto ...