VueJS and firebase: Check if the user is logged in after page refresh
P粉680487967
P粉680487967 2023-08-28 22:02:53
0
1
491
<p>I am developing a web application using Vue 3 and firebase framework. As a stroe, I use Pinia. For authentication I'm using firebase and so far it works great, users can register and log in. Once a user logs in, his data is stored in pinia storage. </p> <p>However, once the user logs in and reloads the page, the data in pinia storage is lost. If I use the firebase function <code>onAuthStateChanged()</code> , the user is still logged in. </p> <p>My first solution was to call the <code>onAuthStateChanged()</code> function every time the app is launched and the pinia store is populated with the required data. I've tried calling the <code>onAuthStateChanged()</code> function in the firebase config file, but the pinia store hasn't been initialized there yet. </p> <p>At what point in the Vue application do I have to call the <code>onAuthStateChanged()</code> function so that the user is automatically logged in after a refresh and I can write user data to Pinia storage? </p>
P粉680487967
P粉680487967

reply all(1)
P粉195402292

I'm not sure what you've tried, but I know this will work. Of course, you can move onAuthStateChanged out of your store and it will still work. Remember, you have to use observers or computed props 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 = ...
    }
  }
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!