I’m trying to use Firebase Authentication with VueFire inside a Pinia Store to keep my code clean and have app wide access to the user data, but when I try to access the Auth instance with const auth = useFirebaseAuth()
my app throws this warning:
inject() can only be used inside setup() or functional components.
And when I try to run any of the Firebase Auth methods I get this error:
Cannot read properties of undefined (reading 'app')
This is my UserStore.js:
import { defineStore } from 'pinia'
import router from '../router/index'
import { useFirebaseAuth } from 'vuefire'
import { signOut, createUserWithEmailAndPassword, signInWithEmailAndPassword } from 'firebase/auth'
const auth = useFirebaseAuth()
export const useUserStore = defineStore('UserStore', {
state: () => {
return {
user: {},
isLoggedIn: false,
email: '',
password: '',
repassword: '',
errorMessage: '',
}
},
actions: {
async register() {
if (this.password === this.repassword) {
await createUserWithEmailAndPassword(auth, this.email, this.password)
.then((userCredential) => {
const user = userCredential.user
console.log(user)
router.push('/:placeName')
})
.catch((error) => {
const errorCode = error.code
console.log(errorCode)
this.errorMessage = error.message
alert(this.errorMessage)
})
} else {
alert('Passwords must match')
}
},
async login() {
await signInWithEmailAndPassword(auth, this.email, this.password)
.then((userCredential) => {
const user = userCredential.user
console.log(user)
router.push({ name: 'menu' })
})
.catch((error) => {
const errorCode = error.code
console.log(errorCode)
this.errorMessage = error.message
alert(this.errorMessage)
})
},
async signout() {
await signOut(auth)
.then(() => {
router.push({ name: 'login' })
})
.catch((error) => {
const errorCode = error.code
console.log(errorCode)
this.errorMessage = error.message
alert(this.errorMessage)
})
}
}
})
If I move const auth = useFirebaseAuth()
inside the State everything works just fine but I’m not sure if that’s the right way to do that.