Having trouble with Vue component not updating Vuex state before it loads?

At times, the token is committed to Vuex store while other times it is not.

userLogin() {
  axios.post('api/login', this.logindata,)            
  .then(response => {
    let token = JSON.parse(localStorage.getItem('token'));

    this.$store.commit('setToken', token);
    this.logindata = {};
    this.loaded = true;
    this.success = true;
    this.$router.push({path: '/'});
  });
}

Below is the store.js:

export default new Vuex.Store({
  state: {
    token: JSON.parse(localStorage.getItem('token')),
    isLoggedIn: !!localStorage.getItem('token'),
    cart: []
  },
  mutations: {
    setToken(state, token) {
      state.token = token;
    },
  }
});

Here is Vue Frontend:

mounted: function () {       
  if (!this.$store.state.isLoggedIn) {
    this.$router.push('/login')
  }
}

Outcome: there are occasions when it redirects to login and instances where it does not. Any insights on how to address this issue?

Answer №1

To ensure that the component is only loaded after a user logs in, you can use a v-if directive along with a computed property that listens for changes in the login status.

<myComponent v-if="computedProperty"/>
computed: {
 computedProperty(){
   return this.$store.state.isLoggedIn
...

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

Locating the matching value in the <select> element and showcasing it

I'm trying to create a function where selecting an option from one dropdown menu will display the corresponding value in another column. For instance, if someone chooses "3" from the first dropdown, the value displayed in the third column should be "3 ...

Sending a multitude of variables using strings, evaluating them through various functions, and incorporating a variety of methods

To put it simply, my goal is to utilize an object literal that allows me to pass an unknown quantity of variables in any order to a function. While this may seem straightforward in principle, within my code, this object literal is passed to a second functi ...

Aggregate array based on specified criteria in ReactJS

Let's consider the following array data: array = [ { id: 1, count: 0.5 cost: 100 user: {id: 1, name: "John 1"}, type: {id: 1, name: "T1"}, period: {id: 1, name: "2021"} ...

What is the process for loading a script file from within a component's HTML?

My goal was to include a specific script file in the component html, but I noticed that when I added the script reference within the html itself, the inner script file was not rendered along with the component on the page. Component import { Component } ...

Tips for aligning a cluster of floating buttons at the center in Vuetify:

This is the code I am currently working with: <v-container height="0"> <v-row align="center" justify="center"> <v-hover v-slot:default="{ hover }" v-for="(option, index) in options" ...

Identifying duplicate values in an array of objects using JavaScript

I am facing an issue with my array that collects data from a spreadsheet into studentCCAList. Sometimes, a student may have multiple subjects. For example, Name: Joseph Subject: English Name: Peter Math Name: Joseph Subject: Science My concern i ...

Having trouble choosing multiple options from autocomplete drop-down with Selenium web-driver in Python

I am currently in the process of automating a webpage built with Angular that features an auto-complete dropdown with numerous elements. My goal is to click on each individual element and verify if it populates all the fields below accordingly. Below is th ...

Ajax handling all tasks except for adding HTML elements

Having an issue with my basic "Load More on Scroll" AJAX function. The console is showing that the HTML is being sent back from the request, but for some reason, nothing is being rendered on the page. I must be missing something really simple here. $(wi ...

Explore the differences between user input and JavaScript

There seems to be an issue with the second output result. var compareNumber = 3; // Code will be tested with: 3, 8, 42 var userNumber = '3'; // Code will be tested with: '3' 8, 'Hi' /* Enter your answer here*/ if (userNum ...

Steps to finish (refresh) a mongoDB record

Currently, I am dealing with the following scenario: An API request from one service is creating multiple MongoDB documents in a single collection. For example: [ {_id: 1, test1: 2, test: 3}, {_id: 2, test1: 3, test: 4} ] Subsequently, a second service ...

How to pass props dynamically to components in VueJS with ease

My view is always changing: <div id="myview"> <div :is="currentComponent"></div> </div> I have linked it to a Vue instance: new Vue ({ data: function () { return { currentComponent: 'myComponent', } ...

Encrypting data using pidCrypt in a combination of Javascript and PHP

Currently, I am in the process of developing an encryption system to secure sensitive information on my website. My web hosting service requires an additional fee for SSL, which I am not prepared to invest in at this moment. I experimented with utilizing ...

Clicking on a href link inside a scrollable div-container causes it to malfunction, causing the page to jump

I have a draggable div container that contains dynamically generated content. In order to display this container, I use the following code: $( function() { $( "#dialog-message" ).dialog({ modal: true, height: 400, buttons: { Fertig: functi ...

Is there a method to retrieve a value from a node.js server when a div is clicked?

This is the EJS file I've created: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Sart Plug</title> <script src="http://code.jquer ...

The initial drag function seems to be dysfunctional in vue-smooth-dnd for vuejs

Check out the code snippet below for a drag and drop section. The div with the class drag-block should be draggable, but it doesn't work on the first attempt; it only drops when we drag it for the second time. https://github.com/kutlugsahin/vue-smoot ...

What could be the reason for my user input not being captured and saved as variable data on the HTML webpage?

Here is the code I am working with: var g = document.getElementById("al").value; function start() { document.getElementById("test2").innerHTML = typeof(g) + parseFloat(g); } <p id="test2">Output will be displayed here:</p> <form> ...

Employing a script that is generated from the jQuery AJAX response

How does using script as the response for a jQuery/AJAX request benefit us? Is it possible to directly run a function from that response script after sending the AJAX request? Any simple examples would be much appreciated. ...

Angular - remove elements from an array within a directive when encountering a source error

If an image does not exist, I need to remove the item and push the next one inside ng-repeat. Currently, I am using a custom directive called "noImage". myApp.directive("noImage", function() { return { link: function(scope, element, attrs) { ...

"Encountering a blank page in React Router when transitioning between separate projects

I've come across some discussions about a similar issue like this one, but I haven't been able to resolve my problem. In my initial project, I can smoothly navigate between its pages. However, when I created a second project hosted in a subdirec ...

Configuring a custom domain for a Rust service on Clever Cloud: A step-by-step guide

After successfully deploying my Rust service to the Clever Cloud platform and testing it on PROD and localhost, I am now facing the challenge of binding my custom domain with the deployed service. I would like to eliminate the need for using the lengthy C ...