skip to Main Content

I am using:

[email protected]
[email protected]
[email protected]

I have created a store for the authentication with a firebase db. The code is as follow:

import { defineStore } from 'pinia'
import { createUserWithEmailAndPassword,signInWithEmailAndPassword,signOut,onAuthStateChanged  } from "firebase/auth";
import { auth } from "@/firebase";

export const useStoreAuth = defineStore('storeAuth', {
  state: () => {
    return {
      user: null,
    }
  },
  actions: {
    init() {
      onAuthStateChanged(auth, (user) => {      
        if (user) {
          this.user = {}
          this.user.id = user.uid
          this.user.email = user.email
        } else {
          this.user = null
        }
      });
    },
    registerUser(credentials) {
      createUserWithEmailAndPassword(auth, credentials.email, credentials.password).then((userCredential) => {
        const user = userCredential.user 
        this.router.push('/')     
      }).catch((error) => {
        console.log('Error while registering:',error.message);
        }
      });
    },...

I am using this.router.push in order to go to the home page after successful registration.

I would like to rewrite my code using the composition API but when I do, I don’t understand how to rewrite my code so that the function registerUser(credentials) can use this.router.push.

I have tried to rewrite it like this:

const registerUser = (credentials) => {
    createUserWithEmailAndPassword(auth, credentials.email, credentials.password).then((userCredential) => {
      const firebaseUser = userCredential.user 
      router.push('/')     
    }).catch((error) => {
      console.log('Error while registering:',error.message);
      }
    });
  }

but it is not working in this case…

2

Answers


  1. in composition api, you can use router with useRouter

    import { useRouter } from "vue-router";
    
    const router = useRouter();
    
    ...andyourcode...
    

    see this page , official vue router site.

    Login or Signup to reply.
  2. You could pass router as an argument of registerUser()

    In your component

    import { useRouter } from "vue-router";
    const router = useRouter();
    ...
    registerUser(credentials, router);
    

    In your store

    const registerUser = (credentials, router) => {
        createUserWithEmailAndPassword(auth, credentials.email, credentials.password).then((userCredential) => {
          const firebaseUser = userCredential.user 
          router.push('/')     
        }).catch((error) => {
          console.log('Error while registering:',error.message);
          }
        });
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search