Update all project files in Firebase authentication

A client-side project is being developed using firebase and vue. After a successful login by the user, the authService object gets updated in the Login component, but not in the router. The authService is utilized in both the Login component and AdminNavbar component. In my understanding, the onAuthStateChanged method should update the user variable at each login and logout event. While this functionality works in the Login component, it does not work in the router, causing the app to always redirect to the login page.

Below is the shared code for firebase and authService:

import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';

const firebaseConfig = {
};

const firebaseApp = firebase.initializeApp(firebaseConfig);

const initializeAuth = new Promise(resolve => {
  firebase.auth().onAuthStateChanged(user => {
    authService.setUser(user);
    resolve(user);
    console.log(user); 
  })
})

const authService = {

  user: null,

  authenticated () {
    return initializeAuth.then(user => {
      return user && !user.isAnonymous
    })
  },

  setUser (user) {
    this.user = user
  },

  login (email, password) {
    firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION).then(function() {
      firebase.auth().signInWithEmailAndPassword(email, password)
    }).catch(function(error) {
      console.log(error);
    });
  },

  logout () {
    firebase.auth().signOut().then(() => {
      console.log('logout done')
    })
  }
}

export const db = firebaseApp.database();
export const hadithRef = db.ref('hadith');
export default authService;

Below is the shared code for the router:

import Vue from "vue";
import VueRouter from 'vue-router';

Vue.use(VueRouter);

// import components
import authService from './firebase.js';

const router = new VueRouter({
    mode: 'history',
    routes: [
      // path, name, and component information are included here
    ]
});

router.beforeEach((to, from, next) => {
    // The user variable is still null even after the user logs in, but it is not null in the Login component.
    console.log(authService.user);
    if (to.path == '/hadith/query' && authService.user == null) next({ path: '/login' })
    else if (to.path == '/hadith/add' && authService.user == null) next({ path: '/login' })
    else if (to.path == '/hadith/update' && authService.user == null) next({ path: '/login' })
    else next()
});

export default router;

main.js code is shared below:

import Vue from 'vue'
import '@babel/polyfill'
import 'mutationobserver-shim'
import './plugins/bootstrap-vue';
import './plugins/vuefire';

Vue.config.productionTip = false;

import App from './App.vue';
import router from './plugins/hrouter';

new Vue({
  render: h => h(App),
  router
}).$mount('#app')

Answer №1

For the solution, you can refer to this helpful link. As explained below, it is recommended to utilize vuex for managing states within the onAuthStateChanged observer method. Additionally, it is important to persist the states of vuex. You may also check out my repository on github here.

To implement this, modify the onAuthStateChanged method in your firebase file as follows:

import store from '../store/index';
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    store.dispatch('setUser', null);
  } else {
    store.dispatch('setUser', null);
  }
});

Furthermore, ensure to install vuex-persistedstate for persisted states by including the following code:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import createPersistedState from "vuex-persistedstate";
export default new Vuex.Store({
  plugins: [createPersistedState()],
  state: {
    user: null
  },
    getters:{
      getUser: state => {
          return state.user;
      }
    },
  mutations: {
    setUser(state, user){
      state.user = user;
    }
  },
  actions: {
    setUser(context, user){
        context.commit('setUser', user);
    },
  }
})

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

Using React hooks to update the state of an array from one component to another

I am currently working on a MERN blog website project and I've encountered an issue while trying to update comments on a post. I'm editing the comment from another component but facing difficulty in updating the state after making changes. Would ...

Activating Unsplash API to initiate download

I am currently following the triggering guidelines found in the Unsplash documentation. The endpoint I am focusing on is: GET /photos/:id/download This is an example response for the photo: { "id": "LBI7cgq3pbM", "width": ...

Grunt: Can you explain the concept of recursive templates?

Hey there, I'm new to using Grunt and I've run into a puzzling issue with recursive templates. Let me provide you with a concrete and straightforward example: var path = require('path'); module.exports = function(grunt) { grunt.init ...

saving user information with asynchronous HTTP calls

I am encountering an issue while trying to save my form data using AJAX. When I submit the form data in a JavaScript file that calls another PHP file to perform an insertion operation, an error occurs. Here is the code snippet: <button id="submit" cl ...

Unusual hue in the backdrop of a daisyui modal

https://i.stack.imgur.com/fLQdY.png I have tried various methods, but I am unable to get rid of the strange color in the background of the Modal. Just for reference, I am using Tailwind CSS with Daisy UI on Next.JS. <> <button className='btn ...

Raphael JS Path Animation: Wiping Away

I have successfully created a line animation using RaphaelJS, which can be viewed on this jsfiddle link - http://jsfiddle.net/7n040zdu/. My next challenge is to create an erasing animation that follows the initial one. This erasing animation should mimic t ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

ESLint only lints certain errors in the command-line interface

Incorporating eslint into my project has been a game-changer. Here's how my .eslintrc file is set up: // http://eslint.org/docs/rules { "parser": "babel-eslint", "env": { "browser": true, "node": true, "mocha": true }, "plugins": ...

Leveraging the power of React Native with embedded RapidAPI functionality in the source

I had previously used the following code to retrieve a JSON file containing personal data in my React Native source code: async componentDidMount() { try { const response = await fetch('mydomain.org/personaldata.json'); const responseJson ...

Enhancing XTemplate in ExtJS 4.2.1 with dynamic data refresh from store

Here's a situation that's quite unique... A DataView linked to a store is causing me some trouble. In the XTemplate, I want to display the quantity of a specific type of JSON record. Each record has a 'type' property with a value. For ...

How can I add text to a textbox within a duplicated div using Javascript or Jquery?

I'm looking to add text to a cloned div's text box using jQuery. I have a div with a button and text box, and by cloning it, I want to dynamically insert text into the new div. $(document).ready(function () { $("#click").click(function () { ...

The splash screen fails to show up when I launch my Next.js progressive web app on iOS devices

Whenever I try to launch my app, the splash screen doesn't show up properly. Instead, I only see a white screen. I attempted to fix this issue by modifying the Next Metadata object multiple times and rebuilding the PWA app with no success. appleWebApp ...

Express JS causing NodeJS error | "Issue with setting headers: Unable to set headers after they have been sent to the client"

As I embark on my journey to learn the fundamentals of API development, I am following a tutorial on YouTube by Ania Kubow. The tutorial utilizes three JavaScript libraries: ExpressJS, Cheerio, and Axios. While I have been able to grasp the concepts being ...

React does not accept objects as valid children. If you want to render a group of children, make sure to use an array instead

I am in the process of developing a system for document verification using ReactJS and solidity smart contract. My goal is to showcase the outcome of the get().call() method from my smart contract on the frontend, either through a popup or simply as text d ...

In the middleware, the request body is empty, but in the controller, it contains content

Below is my server.js file: import express from "express"; import mongoose from "mongoose"; import productRouter from "./routers/productRouter.js"; import dotenv from "dotenv"; dotenv.config(); const app = expres ...

Encountering a User Agent error while trying to update Vue to the latest version using N

I was interested in experimenting with staging.vuejs. When I tried to install it using the command npm init vue@latest, I encountered an error. Here is the link for reference: https://i.stack.imgur.com/rCipP.png SPEC Node : v12.13.0 @vue/cli : v4.5.15 ...

Using the foreach Loop in Javascript and AngularJs

Having trouble with a foreach loop because you're not sure of the column name to access specific data? Here's a solution to display all columns along with their corresponding data: angular.forEach(data, function(value, key) { console.log( &a ...

best practices for transferring object data to a table with ng-repeat

I have an object called 'SEG-Data with the following structure. I am attempting to display this data in a table using ng-repeat. SEG_Data Object {ImportValues: Array[2]} ImportValues: Array[2] 0: Object ImportArray: "004 ...

Undefined variable when initializing with ng-init

As a newcomer to AngularJS (and JavaScript in general), I'm currently facing an issue that I could use some help with. Below is the HTML template I am using: <ion-view view-title="Playlists"> <ion-content> <ion-list> ...

Encountering issues with generating image files using createObjectURL after transitioning to NextJS 13 from version 10

I'm currently working on a website with the following functionality: Client side: making an API call to retrieve an image from a URL Server side: fetching the image data by URL and returning it as an arrayBuffer Client side: extracting the arrayBuffe ...