A
A
Anastasia2021-10-23 13:23:34
Vue.js
Anastasia, 2021-10-23 13:23:34

Why does it take me to the login page when I refresh the page?

Hey everyone
, I'm using Firebase for my Vue app.

When I reload the page, I am always redirected to the login page.
I found this solution:

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import "@/firebase/firebase.js";
import { auth } from "@/firebase/firebase.js";

import Varlet from "@varlet/ui";

import "@/main.scss";

let app;
auth.onAuthStateChanged(() => {
  if (!app) {
    const app = createApp(App);

    app.use(store);
    app.use(router);

    app.mount("#app");
  }
});


The problem with the redirect to the authorization page is gone. But when I log in and the router redirects me to the home page, the application is empty. That is, there is nothing in the app .
Only after reloading the page, the data appears there. But after reloading, a new problem appears:

When I refresh the page, the output of data depending on whether the user is authorized or not does not work correctly:

<div v-if="!isAuthenticated">
  <router-link to="/login">
    Login
  </router-link>
</div>
<div v-else>
<router-link to="/login" @click="logout">
   Logout
</router-link>
</div>


import { mapState } from "vuex";
export default {
computed: {
...mapState(["isAuthenticated"]),
},
methods: {
logout() {
this.$store.dispatch("logout");
},
},
};


Store:
import { createStore } from "vuex";
import * as fb from "../firebase/firebase";
import router from "../router/index";

export default createStore({
  state: {
    userProfile: {},
    isAuthenticated: false,
  },
  mutations: {
    setUserProfile(state, val) {
      state.isAuthenticated = !state.isAuthenticated;
      state.userProfile = val;
    },
  },
  actions: {
    async login({ dispatch }, form) {
      const { user } = await fb.auth.signInWithEmailAndPassword(
        form.email,
        form.password
      );
      dispatch("fetchUserProfile", user);
    },
    async fetchUserProfile({ commit }, user) {
      const userProfile = await fb.usersCollection.doc(user.uid).get();
      commit("setUserProfile", userProfile.data());
      router.push("/");
    },
    async logout({ commit }) {
      await fb.auth.signOut();
      commit("setUserProfile", {});
      router.push("/login");
    },
  },
  modules: {},
});


Tell me, please, what is the problem?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question