Answer the question
In order to leave comments, you need to log in
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");
}
});
<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");
},
},
};
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: {},
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question