Skip to content
Advertisement

how to auth user using async and await in firebase

I have a simple app in Vue.js that authenticates existing users in firebase. So far it works but I want to make it using async and await instead of then? How can I rewrite my logic using async and await instead? I looked at the docs but didn’t find any information, here is my code:

<template>
    <div>
       <form @submit.prevent="userLogin">
            <h3>Sign In</h3>

            <div>
                <label>Email address</label>
                <input type="email"  v-model="user.email" />
            </div>

            <div>
                <label>Password</label>
                <input type="password"  v-model="user.password" />
            </div>

            <button type="submit" >Sign In</button>
        </form>
    </div>
</template>

<script>
import firebase from 'firebase'

export default {
    name: 'Login',
    data() {
    return {
      user: {   
        email: '',
        password: ''
      }
    };
  },
  methods: {
   userLogin() {
        firebase
        .auth()
        .signInWithEmailAndPassword(this.user.email, this.user.password)
        .then(() => {
            this.$router.push('/')
        })
        .catch((error) => {
          alert(error.message);
        });
    }
  }
}
</script>

Advertisement

Answer

define the property as an async function. remeber to use function() {} and not () => {} otherwise you lose context of this

<script>
import firebase from 'firebase'

export default {
    name: 'Login',
    data() {
    return {
      user: {   
        email: '',
        password: ''
      }
    };
  },
  methods: {
   userLogin : async function () {
      try {
        await firebase.auth().signInWithEmailAndPassword(this.user.email, this.user.password)

        this.$router.push('/')
      }
      catch(e){
          alert(error.message);
      }
    }
  }
}
</script>
Advertisement