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

Is nextJS SSR the optimal solution for handling undefined variables in the window object to enable optional chaining in cases where global variables are not supported?

When using (window?.innerHeight || 420) for server-side rendering (SSR), the translation would be (((_window = window) === null || _window === void 0 ? void 0 : _window.innerHeight) || 420) However, this could result in a referenceError: window is not d ...

What is the best way to implement client-side shopping cart calculations using jQuery?

https://i.stack.imgur.com/aOajr.png Here is the content of my shopping cart. Below, I will explain the flow. [product image clicked] -> ajax request fetches details from database for that particular product id and appends (product name,id and price ...

Tips for incorporating flow and TypeScript typings into an NPM module

Are there any resources available for adding both flow and typescript typings to an NPM module at the same time? I've been struggling to find a comprehensive guide on this topic, and it seems to be a common issue faced by open source library maintain ...

Are you experiencing a strange problem with the CSS button when hovering, clicking, or with the border?

Check out the code for this implementation on jsfiddle: https://jsfiddle.net/xuhang1128/cmkbu07s/2/ I utilized React and React-bootstrap to create it. .design2-statusMonitor { margin-top: 20px; .list-group-item { display: inline-block; ...

Ensuring that the selected item in a Vuetify combobox is included in its list of available options

Ensuring that the option chosen by the user in vue-combobox belongs to the available choices is important to me. ...

Is there a way for me to figure out if a Primefaces RadioCheckbox has been selected?

Despite the numerous examples available on how to count checked checkboxes, I am facing difficulties in getting it to work. My goal is to enable a button when at least one checkbox is checked on the page, and disable it when none are selected. However, n ...

Using PHP's include/require method with a dynamic path

Looking for assistance with my issue! Ajax is returning the correct information and displaying it in an 'alert(html)' on 'success'. The PHP code echoes $idName and $path correctly on the carrier page where the code resides. There are no ...

What is the method for altering the state of a single element within a map?

As I delve into learning React, I encountered a persistent issue that has been absorbing my time for several hours now. The problem revolves around mapping an array of product sizes to buttons and controlling the state change of only the last clicked butto ...

Update the chosen option in a dropdown list with jQuery and javascript

I need to set the value of a column in a repeater so that once it's assigned, the column will display the current selection from the dropdown. I have the correct value to assign in $('#myname_' + rowIndex).text(), but when I try to assign t ...

React - utilizing dynamic properties using string values

I am facing a challenge in my test suite where I need to generate components with dynamic props. The desired components should look like this: <Button primary /> <Button secondary /> However, I am currently stuck at this point: [ &apos ...

Adjusting package.json settings for an npm module

An npm package that I am using has an incorrect file path specified in its package.json. The current configuration is: "main": "./htmldiff.js", However, for it to function correctly, it should be: "main": "./src/html ...

Attempting to display a v-data-table inside a v-dialog results in rendering issues

I'm currently working on incorporating a v-data-table in a v-dialog <v-dialog max-width = '600px' v-model = 'dialog'> <v-card> <v-card-title> <span class = "headline"> Reconstru ...

UI-Router: What is the best way to access a page within my project without adding it as a State?

Currently in the process of learning Angular and UI-Router. Initially, I followed the advice of many and chose to utilize UI-Router. In my original setup, the login page was included in all States. However, I decided it would be best to keep it as a separ ...

Error message: App not defined in Ember App.router

Attempting to set up routing for my app for the first time, but struggling to grasp the logic. I managed to render my templates by adding the following code to my route.js file: import Ember from 'ember'; import config from './config/enviro ...

Experiencing issues calling a function in Vue.js while working with the SDK JavaScript?

When attempting to integrate the JavaScript SDK into Vuejs by utilizing a Facebook login button, I encountered an issue: <template> <div> <div class="fb-login-button" data-max-rows="1" data-size="large" data-button-type="login_with" d ...

Separate a string using commas but disregard any commas inside quotation marks

Similar Question: JavaScript code for parsing CSV data There is a string that looks like this: "display, Name" <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d49584e497d49584e49135e5250">[email protected]</a> ...

Utilize the ng.IFilterService interface within a TypeScript project

I am facing an issue with a .ts file that contains the following code: module App.Filters { export class SplitRangeFilter implements ng.IFilterService { static $inject = ['$filter']; public static factory(): Function { ...

Obtain information from an ajax request

I am working on a website where I need to implement a button that checks if the user has specific permissions before opening a new web page in a popup window. In my JavaScript code, I have the following function: function sendAjax(methodName, dataArray, s ...

Is add1 missing from the DOM? Learn how to include it

Having an issue with Java-Script and an HTML form. The scenario is that there's a main form with an "Add" button, which when clicked should display a second form. Next to the second form is another button labeled "Add1," which ideally should trigger ...

Executing an AJAX POST request from one domain (localhost:9393) to another domain (localhost:9696) using Spring Rest

I am encountering an issue with a form on one app running on localhost:9393. The JavaScript function used to post data is: function registerClient() { var postData = $("#client-reg").serializeArray(); var formURL = "http://localhost:9393/mPaws/client/re ...