Home » vue » Vuejs check if cookie is set without page refresh

Vuejs check if cookie is set without page refresh

Posted by: admin November 26, 2021 Leave a comment

Questions:

What I want to do with VUE at the moment is when the user log in the login url would disappear from the navigation.

Currently, I can log in and token cookie is set successfully in the browser. But the problem is while I won’t refresh my page the login url won’t disappear from the navigation bar. Heres some code examples:

Login.vue sets the cookie and redirects me to home when I log in:

if(response.status === 200 && response.data.success && response.data.token) {
  const token = response.data.token;
  this.$cookie.set('token', token);
  this.$router.push({name: 'home'});  

Then in Navigation.vue I check if the cookie exists:

<li class="nav-item" v-if="!cookie">
    <router-link class="nav-link" to="login">Login</router-link>
</li>  

data: () => {
    return {
        cookie: Vue.cookie.get('token')
    }
},

So the cookie exists after login but VUE understands that only after I hit the refresh button in browser or f5. How can I solve this so the login url disappears immediately after login?

This is my axios configuration:

const axiosInstance = axios.create({
    baseURL: 'http://localhost:3000/',
    headers: {'Content-Type': 'application/json'},
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN' 
});

axiosInstance.interceptors.request.use(
    config => {
      config.headers['Authorization'] = 'Bearer '+ Vue.cookie.get('token');
      return config;
    },
    error => Promise.reject(error)
  );

EDIT

Maybe I can achieve something with VUEX?

EDIT 2

So currently this is my solution:
I’ve added VUEX so the token is set like this also:

  this.$cookie.set('token', token);
  this.$store.state.cookie = this.$cookie.get('token');
  this.$router.push({name: 'home'});

And in my Navbar.vue I do this:

computed: {
    cookie() {
        return this.$store.state.cookie
    }
},

and then check like this:

<span v-if="$cookie.get('token') || cookie">
    Log out
</span>
<span v-else>
    <router-link class="nav-link" to="login">Login</router-link>
</span>  

$cookie.get('token') || cookie so the cookie is from VUEX which checks it without page refresh but after page refresh VUEX state is gone. So then after page refresh $cookie.get('token') works.

Answers:

Essentially, you want to use some sort of event/signaling mechanism to inform different components about the change in a cookie value. Vuex is one mechanism to do that. Alternately, you can use Vue instance as an Event bus channel:

STEP 1: Create Event Bus using Vue in event.js file:

import Vue from 'vue';

export const eventBus = new Vue();

STEP 2: Import it in Login.vue and publish an event when cookie is set:

import { eventBus } from './event.js';

// ... Other code
this.$cookie.set('token', token);

// Publish event
eventBus.$emit('tokenSet', token);

STEP 3: Listen to this event in Navigation.vue:

import { eventBus } from './event.js';



data() {
    return {
        cookie: Vue.cookie.get('token')
    }
},

created() {
    eventBus.$on('tokenSet', (token) => this.cookie = token);
}

This way your cookie becomes reactive by updating whenever tokenSet event is fired. With this, you really don’t need to refresh the page and even if refreshed, the initial value of the cookie is read by the data function. In a large-scale application, something like Vuex or Redux is a way to go but the underlying idea is still the same.

For more details refer to this article.