2

i am using Vuex and Firebase Authentication. I got stuck when reload the page. firebase.auth().onAuthStateChanged take time to response. But i need at the same time when reload the page. I have seen many tutorials in internet, most of them is router guard, but that i don’t want. I have some route where the user has login, then can navigate to this route.

App.vue where i am applying.

created () {
    firebase.auth().onAuthStateChanged(async user =>{
        if (user){
          await this.$store.dispatch('autoSignIn',user)
        }
      })
  }

Here is my vuex action theat trigger when page reload to auto sign in if a user was logged before reload the page.

 autoSignIn ({commit}, payload) {
            commit('setUser',{email:payload.email, userId:payload.uid})

        }

This is my getter

 isAuthenticated:state => {
    return state.user !== null && state.user !== undefined ? state.user : null
 }

Here is where i am calling my getter isAuthenticated.

  getEventsByUser({getters,commit}){

            let data = [];

            firebase.database().ref('usuario/' + getters.isAuthenticated.userId + '/eventos/')
                .on("value", eventos =>{
                     eventos.forEach(evento =>{
                        data.push({"id":evento.key, ...evento.val()})
                    });
                    commit('setEventsByUser',data)
                })

        },

And this is the component which dispatch the action

<template>
    <div>
        <div v-for="(event,id) in getEventsByUser" :key="id">
            {{event}}
        </div>
    </div>
</template>

<script>
    export default {
        name: "MyEvents",

        computed:{
            getEventsByUser(){
                return  this.$store.getters.getEventsByUser;
            },
        },
        mounted() {
            this.$store.dispatch('getEventsByUser')
        },



    }

Here is the error when i reload the page enter image description here

Mohamed Mamun
  • 211
  • 3
  • 15
  • None of the code is trying to read a `userId` as far as I can see, but that's what the error message is about. Are you sure the error is coming from the code you shared? The stack trace seems to point at `getEventsByUser` – Frank van Puffelen Apr 07 '20 at 03:30
  • Hi @Frank van Puffelen, i uploaded the code where use isAuthenticated getter and where use userId – Mohamed Mamun Apr 07 '20 at 03:34
  • I deleted the code from comment box. I am stuck with this, whenever i refresh the page, it's give me this error. Thank you – Mohamed Mamun Apr 07 '20 at 03:39

1 Answers1

0

When the page loads, Firebase checks whether the ID token that is stored for the user is still valid. This requires that it calls the server, so it may take a moment. During this check the user will be null, so your code needs to handle that everywhere.

In your onAuthStateChanged handler you handle this correctly with:

firebase.auth().onAuthStateChanged(async user =>{
    if (user){

But then in getEventsByUser you assume there is a user, which (as shown by the error message) is not true. So you'll want to add a check there, to see if there's a user, before attaching the listener to the database:

getEventsByUser({getters,commit}){
    let data = [];
    if (getters.isAuthenticated) {
        firebase.database().ref('usuario/' + getters.isAuthenticated.userId + '/eventos/')
        ...
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Then how can i do that? Wait until get the user, then execute the code in getEventUser. I really git stuck here. – Mohamed Mamun Apr 07 '20 at 03:57
  • I implemented the condition you said, with else statement. But i want get the user value. How can i do that? – Mohamed Mamun Apr 07 '20 at 04:17
  • If there is no signed in user, you can't get the data for a user yet. But the `onAuthStateChanged` should fire soon after when Firebase has checked/refreshed the token, at which point you **can** load their data. – Frank van Puffelen Apr 07 '20 at 13:13