Skip to content

Instantly share code, notes, and snippets.

@fredgdaley2
Last active October 4, 2024 15:11
Show Gist options
  • Select an option

  • Save fredgdaley2/e59b2f82e9b39fd2fbb7f7a3d0ae02a7 to your computer and use it in GitHub Desktop.

Select an option

Save fredgdaley2/e59b2f82e9b39fd2fbb7f7a3d0ae02a7 to your computer and use it in GitHub Desktop.
Vue Pinia Store with router
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
const pinia = createPinia()
createApp(App)
.use(pinia)
.use(router)
.provide('router', router)
.mount('#app')
import { ref, inject } from 'vue'
import { defineStore } from 'pinia'
import { auth } from '@/js/firebase'
import {
createUserWithEmailAndPassword,
signOut,
signInWithEmailAndPassword,
onAuthStateChanged
} from "firebase/auth"
import { useStoreNotes } from '@/stores/storeNotes'
export const useStoreAuth = defineStore('storeAuth', () => {
const router = inject('router');
const appUser = ref({})
/* init */
const init = () => {
const storeNotes = useStoreNotes()
onAuthStateChanged(auth, (user) => {
if (user) {
const uid = user.uid;
appUser.value = {
email: user.email,
id: user.uid
}
storeNotes.init()
router.push('/')
console.log({ appuser: appUser.value.id });
} else {
appUser.value = {}
storeNotes.clearNotes()
router.replace('/auth')
console.log('signed out');
}
})
}
/*
register user
*/
const registerUser = (credentials) => {
createUserWithEmailAndPassword(auth, credentials.email, credentials.password)
.then((userCredential) => {
const user = userCredential.user
//console.log({ user : userCredential.user})
})
.catch((error) => {
const errorCode = error.code
const errorMessage = error.message
//console.log(errorMessage)
})
}
/*
logout
*/
const logOut = () => {
signOut(auth).then(() => {
//console.log('Signed out')
}).catch((error) => {
//console.log('sign out error',error.message)
})
}
/*
login
*/
const loginUser = (credentials) => {
signInWithEmailAndPassword(auth, credentials.email, credentials.password)
.then((userCredential) => {
const user = userCredential.user;
//console.log(user);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
//console.log('login error', errorMessage);
})
}
return {
appUser,
registerUser,
logOut,
loginUser,
init
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment