Make sure to prevent losing the global status in Vuex and VueRouter when the page is refreshed

As I develop a Single Page Application (SPA), I am utilizing Vuex to manage session states on the client side. However, I have noticed that the state resets whenever the browser is manually refreshed. Is there a way to prevent this behavior without relying solely on local storage? And if using local storage is necessary, how can I access the initial state stored there?

Navbar Component

<template>
    <div>
        <ul v-if="!isLogued">
            <router-link :to="{ name:'login'}" class="nav-link">Login</router-link>
        </ul>
        <ul  v-if="isLogued">
                <a href="#" class="nav-link">Profile</a>
                <a href="" @click.prevent="logout">Logout</a>
        </ul>
    </div>
</template>
<script>
    import {mapState,mapMutations  } from 'vuex';
    export default{
        computed : mapState(['isLogued']),
        methods:{
            ...mapMutations(['logout']),
        }
    }
</script>

Store.js

export default {
    state: {
        userLogued: {},
        api_token  : '',
        isLogued : false
    },
    mutations: {

        login( state){
            state.userLogued = JSON.parse(localStorage.getItem('usuario'));
            state.api_token = localStorage.getItem('api_token');
            state.isLogued =  true
        },

        logout(state){
            state.userLogued = {}
            state.isLogued = false
            state.api_token  = null
            localStorage.clear()
        }
    }
};

App.JS

Vue.use(VueRouter)
Vue.use(Vuex)

import store from './vuex/store';
import routes from './routes';
const router = new VueRouter({
    mode: 'history',
    routes
})

const app = new Vue({
   router,
   store : new Vuex.Store(store)
}).$mount('#app')

Within my login component, after making a successful Axios POST request, I handle the response as follows:

   methods : {
        ...mapMutations(['login']),
        sendLogin(){
            axios.post('/api/login' , this.form)
                .then(res =>{
                    localStorage.setItem('api_token', res.data.api_token);
                    localStorage.setItem('user_logued', JSON.stringify(res.data.usuario));
                    this.login();
                    this.$router.push('/');
                })

Answer №1

To maintain data across page reloads and browser sessions, it's important to utilize a persistent storage solution. Options like localStorage, sessionStorage, cookies, and indexeddb are available to suit your specific needs. Keep in mind that sessionStorage is only useful for the current session.

If you need to restore the initial state of your Vuex store, consider using a plugin like vuex-peristedstate. This plugin simplifies the process of saving and restoring Vuex to storage.

Implementing vuex-persistedstate in your store can be done effortlessly by creating an instance as shown below:

import createPersistedState from 'vuex-persistedstate'

const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()]
})

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

The declaration of 'exports' is not recognized within the ES module scope

I started a new nest js project using the command below. nest new project-name Then, I tried to import the following module from nuxt3: import { ViteBuildContext, ViteOptions, bundle } from '@nuxt/vite-builder-edge'; However, I encountered th ...

Ensure that the date input is formatted in ISO standard, but showcase the date according to the user's

Looking to implement the date picker component with localization support, I have created an example of a customized date picker. HTML: <div id="app"> <v-app id="inspire"> <v-menu :value="showDatePicker" max-width="290px" &g ...

The Google Pie chart is displaying outside of the designated div area when placed inside a dropdown menu

Encountering an issue with my pie chart rendering outside of its parent div when placed within a dropdown menu. The chart successfully loads after the page is loaded, but only displays correctly if I hover over the dropdown and allow it to load. If I do ...

Adding a delay to your JQuery wiggle effect

Is there a way to achieve an effect similar to the JQuery wiggle plugin? Check out this demo: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js" type="text/javascript"></script> <script src="http://static.manpoints.u ...

Transferring a JavaScript element's ID to PHP

Recently, I came across a JavaScript function that automatically updates the date and time for me. I found the script on this URL: http://jsfiddle.net/pLsgJ/1/ setInterval(function() { var currentTime = new Date ( ); var currentHours = curren ...

Display confirmation pop-up when clicking outside of the modal window in Bootstrap

I am currently utilizing AngularJS (1.5.9) and ui-bootstrap in my application. I am looking to display a confirmation popup if the user clicks outside of an already open modal. I have attempted using both controlled exit with $uibModalInstance.close() and ...

Can someone guide me on how to make an array filled with dates using Javascript?

I am working on developing a Javascript code that can identify all the days leading up to the current date. Here is what I have managed so far: var titleArray = [ "title1", "title2", ]; var pictureArray = today.toString(); var thumbArray = today.toString ...

[VUE ALERT]: Issue found in mounted hook: "The variable this.$refs.canvas is not defined."

I have integrated Vue Chart into one of my projects, but I am encountering an error. Here is the code for the Chart Component: <line-example></line-example> And below is my script: <script> import Navbar from '@/components/navb ...

Generating Placeholder Variables Within a v-for Iteration

Encountering a problem with Vue-JS involving v-for loops and v-model properties. I have an array of items: <input v-for="i in list" v-model="i.model" ... (other tags that use i) > </input> Accompanied by some JavaScr ...

Tips for expanding a fabric canvas to match the entire width of its parent division

specific scenario I have a cloth canvas placed inside a main section. How can I expand the canvas to cover the entire width and height of its container? Here is what my current code looks like: <div class="design_editor_div"> &l ...

Using Vuelidate with Vue 3, vue-class-component, and TypeScript combination

Is there anyone who has successfully implemented Vuelidate with Vue 3 using the Composition API? Although Vuelidate is still in alpha for Vue 3, I believe that if it works with the Composition API, there must be a way to make it work with classes as well. ...

Is it possible to integrate a standard drop-down menu/style into a MUI Select component?

I am currently working on implementing the default drop-down menu style for my MUI Select Component. Here is the desired menu appearance: https://i.stack.imgur.com/GqfSM.png However, this is what my current Select Component looks like: https://i.stack. ...

Is there a different method to retrieve language bundles with next-i18next instead of using a customized Node server?

Currently, I am developing a Next.js application that will utilize i18next translations organized in the recommended file structure for bundles. For example: static/locales/en/common.js static/locales/de/common.js You can refer to this article: https://m ...

What could be the reason for the history.length being 2 on the initial page?

Why is it that when I open a new browser window and load a page in it, the history.length property is always 2 in both Chrome and Firefox? You can test this phenomenon yourself by visiting the following link: http://jsbin.com/amiyaw ...

The functionality of Ajax is currently disabled on the latest mobile Chrome browsers

I have successfully created a modal form with dependent dropdown lists, and I am populating these lists using an ajax call. The functionality works smoothly on desktop browsers and most mobile browsers, but there seems to be an issue on certain newer versi ...

Arrange the table by adding and editing before and after appending

I have a table data that needs to be dynamically appended. But I want to allow users to add new data using text input and also edit the existing data before and after it's appended. The problem is that when I append new data, it overwrites the previo ...

Which is better: using multiple makeStyles or just one in Material UI?

Uncertain about the best approach in this situation. Is it acceptable to generate styles using makeStyles for each component individually, or would it be better to create one in the base component and simply pass down class names? ...

I discovered an issue in Handsontable while trying to copy and paste a numeric value in German format

For my upcoming project, I am looking to incorporate the Handsontable JavaScript grid framework. However, I have encountered a small bug that is hindering me from utilizing this library to its fullest potential. The task at hand involves displaying a tabl ...

Discover the method of connecting to a unique JavaScript trigger while utilizing IJavaScriptExecutor

In our web application, we have an event called timelineEventClicked that is created by a custom trigger. canvas.addEventListener('click', function (evt) { evt.stopImmediatePropagation(); var mousePos = ge ...

The connection to MongoDB is failing due to an incorrect URI

I tried setting up mongoDB on my node server and referred to the official MongoDB documentation. Here are the details of my setup: MongoDB version: 4.4.3 Node.js version: v15.7.0 I copied the starter code from MongoDB and here is what I used: const { Mon ...