Search code examples
firebasevuejs3vue-routerpinia

Pinia store (composition api) modify route


I am using:

vue@3.2.47
pinia@2.0.35
vue-router@4.1.6

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...


Solution

  • 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);
          }
        });
      }