Reputation: 201
I am working on a webapp with the frameworks Vue 3 and firebase. As stroe I use Pinia. For authentication I use firebase, which works well so far, users can register and log in. As soon as a user logs in, his data is stored in the pinia store.
However, as soon as the user logs in and reloads the page, the data in the pinia store is lost. If I use the firebase function onAuthStateChanged()
there is still a user logged in.
My first solution was to call the onAuthStateChanged()
function every time the app is started and the pinia store is then filled with the required data. I already tried to call the onAuthStateChanged()
function in my firebase config file, but the pinia store is not initialized here yet.
At which point in the Vue app must the onAuthStateChanged()
function be called so that the user is automatically logged in after a refresh and I can write the user data to the Pinia store?
Upvotes: 0
Views: 826
Reputation: 41
I am not sure what you have tried but I know this will work. You can, of course, move the onAuthStateChanged out of your store and it will still work. Keep in mind you will have to use a watcher or computed prop to track store.user and update the UI.
import { getAuth, onAuthStateChanged } from 'firebase/auth';
const auth = getAuth();
onAuthStateChanged(auth, async () => {
const store = useStore();
store.setUser();
});
const useStore = defineStore('store', {
state: () => ({
user: null
}),
actions: {
setUser() {
// Set user here
// this.user = ...
}
}
});
Upvotes: 1