Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh required to detect authentication state using nuxt auth module

My app is unable to detect the state change that occurs when a user logs in without completely refreshing the page. Upon refreshing everything displays correctly. I am using Nuxt and its included auth module documented here - https://auth.nuxtjs.org/.

Here is the v-if statement that is unable to detect the state change:

  <template v-if="$auth.$state.loggedIn">
    <nuxt-link
      to="/profile"
    >
      Hello, {{ $auth.$state.user.name }}
    </nuxt-link>
  </template>
  <template v-else>
    <nuxt-link
      to="/logIn"
    >
      Sign In
    </nuxt-link>
  </template>

Here is the login method in my login page.

  methods: {
    async onLogin() {
      try{

        this.$auth.loginWith("local", {
          data: {
            email: this.email,
            password: this.password
          }
        });

        this.$router.push("/");

      }catch(err){
        console.log(err);
      }

    }
  }

I tried fetching the state via a computed property but got the same result. I can see the vuex store data change to indicate I am correctly logged in/out in the 'Application' tab in Chrome Dev Tools but the Vue Dev seems to constantly indicate I'm logged in.. Not sure if its just buggy though..

I also encounter the same problem in reverse when logging out. Here's the method:

async onLogout() {
  try{
    await this.$auth.logout();
  }catch(err){
    console.log(err);
  }
}

I am happy to provide further details.

like image 298
newprogrammer Avatar asked Feb 19 '20 20:02

newprogrammer


1 Answers

  1. In store/index.js add this :

     export const getters = {
       isAuthenticated(state) {
       return state.auth.loggedIn
      },
       loggedInUser(state) {
       return state.auth.user
      },
    };
    
  2. In the pages you are suppose to be authenticated

    • use middle ware auth as : middleware: 'auth'
    • use import { mapGetters } from 'vuex'
    • in computed add ...mapGetters(['isAuthenticated', 'loggedInUser']),
  3. you can use loggedInUser to get your user details or check if isAuthenticated

and the logout would work as expected as long as your are importing the map getters in the computed

like image 90
M.abdelrhman Avatar answered Nov 11 '22 04:11

M.abdelrhman