How to show button checking a localStorage key?

Viewed 20

When I log out I delete the token. Here is how I check if the token is deleted:

  const isLoggedOut = () => {
    let token = window.localStorage.getItem('token')
    if (token === undefined || token === null || token.length === 0) {
      console.log("user is logged out")
      return true
    }
    else {
      console.log("user is logged in")
      return false
    }
  }

Inside the navbar I want the Login button to be hidden if the user is logged in. This is how the navbar looks like:

  <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
    <router-link class="navbar-brand" :to="{ name: 'Home' }">Home</router-link>
    <ul class="navbar-nav">
        <li class="nav-item">
            <router-link class="text-white" :to="{ name: 'Login' }" v-if="isLoggedOut">Login</router-link>
        </li>
        <li class="nav-item">
            <router-link class="text-white ml-2" :to="{ name: 'Register' }">Register</router-link>
        </li>
        <li class="nav-item">
            <router-link class="text-white ml-2" :to="{ name: 'Dashboard' }">Dashboard</router-link>
        </li>
        <li class="nav-item">
            <button class="text-white ml-2" @click="logOut">Logout</button>
        </li>
    </ul>
  </nav>
2 Answers

window.localStorage.getItem('token') is not reactive. If the value changes, you will not be notified.

Instead of getting logged in state from localStorage, you can manage it through internal state which will then manage the local storage.

for example:

const token = ref(null);
const setToken = (token) => {
  token.value = token;
  window.localStorage.setItem('token', token)
} 
const clearToken = () => {
  token.value = null;
  window.localStorage.removeItem('token')
}
const isLoggedIn = computed(()=>token.value !== null)

then you can use isLoggedIn as a reactive (computed) value.

You can store this in a separate auth.js and export the methods and token.

IsLoggedOut is a function so you need to 'call' it like IsLoggedOut():

<router-link 
  class="text-white" 
  :to="{ name: 'Login' }" 
  v-if="isLoggedOut()"
>
  Login
</router-link>

 
Related