0

So my problem is that when I log in with firebase and my mounted function should switch the component, I tried a lot of stuff, and nothing works. I just need a way to with what my router will switch the page after I sign in.

<template>
  <div class="vue-tempalte" id="regForm">
    <form>
      <h1 id="middle">Sign In</h1>

      <div class="form-group">
        <label>Email address</label>
        <input type="email" id="email" v-model="email" required />
      </div>

      <div class="form-group">
        <label>Password</label>
        <input type="password" id="password" v-model="password" required />
      </div>

      <button type="submit" @click="login" class="button is-light" id="btn1">
        Sign In
      </button>
    </form>
  </div>
</template>

<style scoped>
</style>

<script>
import firebase from "firebase";
export default {
  name: "login",
  data() {
    return {
      email: "",
      password: "",
    };
  },
  mounted: function () {
    if (firebase.auth().currentUser) this.$router.replace("/HeaderLoggedIn");
  },
  methods: {
    login: function () {
      firebase
        .auth()
        .signInWithEmailAndPassword(this.email, this.password)
        .then((user) => {
          console.log(user.user);
        });
    },
  },
};
</script>
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

2 Answers2

1

The problem is in this code:

  mounted: function () {
    if (firebase.auth().currentUser) this.$router.replace("/HeaderLoggedIn");
  },

Right now you're checking whether the user is signed in when the component is mounted. This happens once, while the user being authenticated at many times, since it is an asynchronous operatation.

You'll want to instead *listen for authentication state changes, as shown in the first snippet in the documentation on determining the signed in user:

  mounted: function () {
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        this.$router.replace("/HeaderLoggedIn");
      }
    });
  },
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

Instead of this method, you can try to set a global router.beforeEach method in your main.js file and check the auth state before entering each page and all in one place, not separate for each page then you can do something based on each state.

Akif
  • 7,098
  • 7
  • 27
  • 53
ali faraji
  • 39
  • 2