Determine if a cookie is set in Vue.js without requiring a page refresh

My current goal with VUE is to make the login url disappear from the navigation bar as soon as the user logs in.

After successfully logging in, the token cookie is set in the browser. However, the issue arises when the login url remains visible in the navigation bar until I manually refresh the page. Here are some code snippets to illustrate this:

In Login.vue, the token is set and the user is redirected to the home page upon logging 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 for the existence of the cookie:

<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')
    }
},

Despite the cookie being set after login, VUE only recognizes it after a manual page refresh using F5. How can I ensure that the login url disappears immediately upon login?

This is my axios configuration setup:

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

Could VUEX help me achieve the desired outcome?

EDIT 2

Here's my current solution: I have integrated VUEX to also set the token like this:

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

In Navbar.vue, I utilize the following approach:

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

and then perform this check:

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

The use of $cookie.get('token') || cookie allows for seamless checking of the cookie status without requiring a page refresh, while still accommodating scenarios where VUEX state might reset upon refresh, necessitating the use of $cookie.get('token').

Answer №1

To effectively communicate changes in a cookie value across different components, it is important to use an event/signaling mechanism. One way to achieve this is by utilizing Vuex or creating a Vue instance as an Event bus channel:

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

import Vue from 'vue';

export const eventBus = new Vue();

STEP 2: Import the Event Bus in Login.vue and trigger an event when setting a cookie:

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

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

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

STEP 3: Handle 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);
}

By following this approach, your cookie will automatically update whenever the tokenSet event is emitted without requiring a page refresh. Even if the page is refreshed, the initial cookie value is retrieved by the data function. While larger applications may benefit from using Vuex or Redux, the fundamental concept remains consistent.

For more information, you can refer to this article.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I show an item repeatedly with each button click in ReactJS?

Currently, I have a setup where I can display a checkbox and its label upon clicking a button. However, the limitation is that only one checkbox can be displayed at a time. Is there a way to modify this so that I can show multiple checkboxes simultaneous ...

Dependency injection of an Angular app factory toaster is causing the application to malfunction

I am currently working on an Angular application that utilizes Firebase as its backend. My goal is to inject 'toaster' as a dependency within my authorization app factory. Below is the initial setup of the app.factory: app.factory('principa ...

Is placing JavaScript on the lowest layer the best approach?

I'm facing a unique situation that I haven't encountered before and am unsure of how to address it. My website has a fixed top header and footer. On the left side, there is a Google Adsense ad in JavaScript. When scrolling down, the top header s ...

margin-top: automatic adjustment, with a minimum of 50 pixels

I am trying to add a minimum of 50px margin to the top of my footer tag using CSS, but I haven't been successful with the min() function. I'm not sure if I am overlooking something or if there is another correct approach to achieve this. * { ...

Creating MySQL query results in Node.js manufacturing process

I am looking to format the MySQL result in Node.js in a specific way. The desired result format should look like this: [ { "m_idx" :1 , "contents" : { "m_name" : "a", ...

Convert the jQuery functions click(), hide(), and fadeIn() into their equivalent native JavaScript functionalities

I'm determined to speed up my page by reducing requests. Does anyone have a solution for keeping the functionality of the code below without having to load the entire JQuery library? $("#div1").click(function () { $("#div2).hide(); $("#div3). ...

Adjusting color of fixed offcanvas navbar to become transparent while scrolling

After creating a navbar with a transparent background, I am now using JavaScript to attempt changing the navigation bar to a solid color once someone scrolls down. The issue is that when scrolling, the box-shadow at the bottom of the navbar changes inste ...

Why is URL Hash Navigation not functioning when linking to a different page's slide on the carousel?

Why isn't the #tag link being recognized? Even though the data-hash items are visible in the URL window, the script doesn't seem to pick them up. The standard script used on the carousel page is as follows: $(document).ready(function() { $( ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

Unable to add new Instance Properties in Vue.js within a Laravel project

I am attempting to develop a localization property similar to __('text') in Laravel blade template. I have set up a global window variable that contains all required data under the name window.i18n Below is my resourses/js/app.js file: require(& ...

Setting up Eslint Airbnb with VScode in a Vue project for optimal code formatting and style enforcement

This is my Vue.js code without proper linting. https://i.sstatic.net/TjiWz.png After running npm run lint --fix The code now looks like this https://i.sstatic.net/o1kUm.png However, when I make changes and press Control + C, it reverts back to the ...

Adding HTML attributes to a VueJS table allows for more customization and control

Is it possible to incorporate HTML/Bootstrap elements into a cell in VueJS? <b-table striped show-empty :items="filtered"> <template slot="top-row" slot-scope="{ fields }"> <td v-for="field in fields& ...

The AnchorEL component becomes unusable once a function has been executed for the first time

I am facing a challenge with anchorRef and struggling to understand how it works as I am new to React and have never used it before. After the onClickAway method is called, Material-UI shows an error stating that the anchorRef is set to null, but this warn ...

Using jQuery, you can enclose a string of text with HTML tags easily

This specific content within the span is being dynamically created by PHP. However, I am uncertain how to efficiently target the text string in order to begin using jQuery. <!-- input: --> <span class="price">RM1,088.00 Annually + RM10.00 Se ...

Ways to minimize an array using group by

I have a large dataset that needs to be grouped by COAGrpCode and ldgrGrp. Specifically, I need to sum the values of Opening, PrdDr, PrdCr, and Closing for each unique combination of COAGrpCode and ldgrGrp. Below is a sample of the data, which consists of ...

Is there a way to display this JSON data using mustache.js without needing to iterate through a

Here is the JSON data: var details = [ { "event": { "name": "txt1", "date": "2011-01-02", "location": "Guangzhou Tianhe Mall" } ...

Issue with Angular.forEach loop malfunctioning

Here is the code for my custom filter that includes a parameter called viewbookoption, which is a dropdown value. Depending on the selected value from the dropdown, the data will be displayed in a grid. I have used a forEach loop in this filter, but it see ...

Differences between applying addClass(undefined) and addClass(null)

At times, it crosses my mind to include a class in a chain, depending on certain conditions. What would be the most fitting semantic value to add no class? For instance: $(".element").performAction().addClass(condition ? "special-class" : undefined).perf ...

When attempting to display the details of each restaurant on my detail page, I encountered the error "Cannot read property 'name_restaurant' of undefined."

I have set up dynamic routing for a ProductDetail page, where each restaurant has its own details that should be displayed. The routing is functional, but I am facing difficulty in retrieving data from Firestore using the restaurant's ID. PS: Althoug ...

Using the Map Function in React JS to Dynamically Render Radio Buttons with Material-UI

Hey everyone, I'm looking for some assistance in replacing the old classic radio button with a new one using material-ui. I've been trying but haven't been successful so far. Any suggestions would be greatly appreciated. Thanks in advance. Y ...