Tips for preserving login session continuity following page refresh in Vuejs

signInMe() {
 
      this.$store.dispatch('setLoggedUser', true);
      this.$store.dispatch('setGenericAccessToken', response.data.access_token);

     
      this.errorMessage = "";
    }, (error) => {
      if (error) {
        this.errorMessage = error.response.data.message;
        this.isLoginFailed = true;
        this.emailFailureCount = this.emailFailureCount + 1;
       
      }
    }).catch(error => {})
},

logout() {
  localStorage.clear();
  localStorage.setItem('userType', "G");
  this.$store.dispatch('setLoggedUser', false);
  this.$store.dispatch('setAccessToken', '');
  this.$router.push('/')
  this.registeredUser = false;
},
<div class="myprofileroute" @click="logout">Logout</div>

Upon successful login with valid credentials, I can navigate to a specific page. However, the problem arises when I find myself logged out even without explicitly clicking the logout button. This unexpected logout occurs even upon refreshing the page.

Answer №1

To ensure seamless access, store the access token in your local/session storage and verify its existence on every page load.

async login(){
  try{
    const userData = await axios.post('yourapi');
    const token = userData.access_token;
    localStorage.setItem('userData', userData);
    localStorage.setItem('accessToken', token);
    this.$router.push('/dashboard');
  }catch(err){
     //Handle errors
  }
}

You can also handle it within your main layout or Vue instance:

mounted(){
  const userData = localStorage.getItem('userData');
  const accessToken = localStorage.getItem('accessToken');
  localStorage.setItem('userType', "G");
  this.$store.dispatch('setLoggedUser', userData);
  this.$store.dispatch('setAccessToken', accessToken);
}

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

Leveraging the Scroll feature in Bootstrap for smooth scrolling

Seeking assistance with implementing scroll in Bootstrap 5 on my child component (ProductList.vue). Can anyone guide me on how to integrate the code? I have been searching for a solution without success. Below is the Bootstrap 5 code on the child component ...

Dealing with a routing issue in node.js/express involving JavaScript and CSS

I'm facing an issue. I need to set up a route from localhost.../cars to localhost../bmw/x1 On the localhost../cars page, there's a button that, when clicked, should load localhost../bmw/x1 This is the JavaScript code I have: const express = req ...

Encountering a syntax error while utilizing a JavaScript variable in a jQuery selector for a lightbox feature

I'm currently working on creating a lightbox feature and have reached the stage where I am implementing next and previous buttons to navigate through images. I am utilizing console.log to check if the correct href is being retrieved when the next butt ...

Using jQuery to toggle sliding the information above a div

I am facing an issue with my customized sliding menu. The menu slides over the image but not over the content-div, pushing it aside. I have tried to fix this problem but haven't found a solution yet. My goal is for the menu to slide over all divs and ...

When the class changes, V-for re-renders every component

Currently, I am in the process of changing classes for images based on their index using the moveIndex method and key events. While this works smoothly on computers, it seems to take significantly longer when implemented on TVs. The process runs smoothly w ...

When I refresh the page in Angular2, the router parameters do not get loaded again

When loading my application on routers without parameters, everything is normal. However, when trying to use a router with params, the application fails to load. For example: localhost:3000/usersid/:id The code for the router is as follows: const appRou ...

Challenges with date formatting arise for Spanish speakers when the date returns as NaN or an Invalid

I have been working on an Angular app Objective: My aim is to allow users to input dates in Spanish format (DD/MM/YYYY) and display them as such, while converting them back to English format when saving the data to the Database. Issue: One problem I enco ...

In search of an effortless method to effortlessly select numerous elements using a handy bookmarklet

My goal is to develop a bookmarklet that can perform various functions on different webpages with ease. The concept involves placing it in a convenient location, such as the bookmark bar, and executing a "standard function" on a particular page. Instead of ...

What is the best way to create a sliding animation on a div that makes it disappear?

While I may not be an expert in animations, I have a question about sliding up the "gl_banner" div after a short delay and having the content below it move back to its original position. What CSS properties should I use for this animation? Should I use css ...

"I encountered an error while sorting lists in Vue 3 - the function this.lists.sort is not

Creating a Vue 3 front-end template: <template> <div class="container"> <router-link to="/user/create" class="btn btn-success mt-5 mb-5">Add New</router-link> <table class=" ...

When using the UI Router, nested views may display double slashes in the URL and redirect back to

I've been working on editing a project to incorporate a root view/state that encapsulates all other views/states within it. Previously, each page functioned as an independent state, making it cumbersome to implement global changes across all states wi ...

Unable to insert HTML code into a div upon clicking an image button

I am in the process of developing a website dedicated to radio streams, and I was advised to utilize Jquery and AJAX for loading HTML files into a div upon button click. This way, users wouldn't have to load an entirely new page for each radio stream. ...

Is my Socket.io application consuming excessive bandwidth? What might be causing this issue?

Upon reviewing my AWS billing report, I noticed an excessive data transfer of 495.385 GB on my socket.io application running on the EC2 instance. This amount seems too high for a small experimental website like mine. Could this be due to inefficient code i ...

The unhandled type error rises with each scroll I make

Having been diligently working on my current website project, I encountered a puzzling issue. Upon writing code to implement smooth scrolling throughout the site, I found myself facing a persistent error that continues to escalate with each scroll up or do ...

Is there a way to verify that all CSS files have been successfully downloaded before injecting HTML with JavaScript?

I am looking to dynamically inject HTML content and CSS URLs using JavaScript. I have more than 3 CSS files that need to be downloaded before the content can be displayed on the page. Is there a way to check if the aforementioned CSS files have finished ...

Identifying and implementing page language in nextJS: Solving the ReferenceError "window is not defined" issue

I am currently working on developing a website that can automatically detect the user's country and set the language accordingly. In React, I usually achieve this by using window.navigator.language. Here is a snippet of the code: import * as pt from ...

Tips for dynamically resizing a div element as a user scrolls, allowing it to expand and contract based on

I was working on a project and everything seemed easy until I hit a roadblock. What I am trying to achieve is expanding a div to 100% when scrolling down to the bottom of the div, then shrink it back to 90% at the bottom and do the reverse when scrolling ...

Is it feasible to conceal certain parameters within a URL using Angular UI Router?

Looking to pass two values to a new ui-view via parameters: item id list of objects However, I want the new view to display only the id in the browser URL and not the stringified array of objects: http://www.myapp.com/#/my-view/4 INSTEAD OF http://ww ...

Utilize VUE components for rendering v-html

I'm currently working on developing a unique VUE component preview feature, reminiscent of JSFiddle or CodePen, within the VUE framework. The specific VUE container responsible for previewing the components is outlined as follows: <quickpreview v- ...

Guide on retrieving a value from a function that invokes $.getJSON

function searchAndRetrieve(searchTerm) { var defaultResult = 1010; var resultValue = defaultResult; $.getJSON(remote, function(data) { if (data != null) { $.each(data.items, function(i, item) { ...