Search code examples
javascriptfirebasevue.jsgoogle-cloud-firestorepinia

VUE Need Pinia store info before mounted hook to retrieve from database


I am building a VUE application that uses Pinia as a store and Firebase as a database. I am trying to access a collection from Firebase on page load that requires me to have the logged in users uid.

Currently, I have stored the user.uid inside a user store created by Pinia. The two hooks I have used are setup and async created. When running this, the error I get is that this.authStore.user.uid evaluates to undefined.

setup(){
    const db = getFirestore(firebaseApp);
    const authStore = useAuthStore();
    return { authStore,db,};
  },
  
async created(){
    const q =  query(collection(this.db,this.authStore.user.uid)); //This does not exist
    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      this.data[doc.id] = doc.data();
      // console.log(doc.id, " => ", doc.data());
    });  
  },

I believe I need a method to delay the running of the function within created, however I am not sure how to wrap the whole code block in an await function to wait for the value uid to be available.


Solution

  • I manage to get it to work using v-if and watch. I added in a number that increments each time the page is loaded via the mounted() hook. I have a watcher that watches the number variable that triggers the async function to get data from Firebase.

    data(){
        return {
            triggerWatcher:0
            }
    },
    mounted(){
        this.triggerWatcher += 1    
    },
    watch:{
        async triggerWatcher(){
            //async code that returns data from Firebase
            }
    }
    

    This seems to be quite stable for the time being; this solves the problem of not being able to call the async doe that returns data from Firebase in the mounted, created, beforeMount hooks as the user.uid needed to do that is not populated yet.