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 instance is referencing "firstName" during render, but it has not been defined as a property or method

I am encountering a persistent warning message related to the inputs on my Signup.vue page. This warning is appearing for all four input fields in my code: firstName lastName email password The warning mentioning specific instances keeps popping up consi ...

Organize Dates in React Table

I need help with sorting the Date column in my code. Currently, the sorting is being done alphabetically. Here is the JSON data and code snippet: JSON [ { "date": "Jun-2022" }, { "date": "Jul-2022" } ...

Navigating up and down effortlessly using bootstrap

My webpage has a collapsible form located near the bottom, but when it's opened users must scroll down to see all of it. Is there a way to automatically scroll down when it's opened and then scroll back up when closed? Take a look at my code: & ...

Load an external script once the page has finished loading by leveraging the power of $(document).ready() in conjunction with $.getScript()

Is it possible to load a script in the header of a website instead of at the bottom? I've been trying but it's not working as expected. Here is an example of what I'm attempting: HTML file: <!DOCTYPE html> <html lang="en"> < ...

The arrangement of a JSON array can be modified by AngularJS' Ng-repeat functionality

Hello everyone at SO: On March 18, 2014, I encountered a situation while trying to use ng-repeat. The elements inside the array, retrieved from a Json string, seem to be changing their original order. To clarify, the initial variables in the array pertai ...

What is the reason for receiving the "Must provide query string" error when using the fetch API, but not when using cURL or Postman?

I've been attempting to integrate the graphbrainz library into a React app using the fetch API. No matter how I structure my request body, I keep encountering this error: BadRequestError: Must provide query string. at graphqlMiddleware (C:\U ...

Having trouble retrieving data from a JSON object that has been stringified. This issue is arising in my project that utilizes Quasar

I successfully converted an excel spreadsheet into a JSON object by using the xml2js parseString() method, followed by JSON.stringify to format the result. After reviewing the data in the console, it appears that I should be able to easily iterate through ...

Prop in a React component is undergoing mutation

I encountered a strange situation where a prop in a React component is being changed. Although it's technically not a mutation since it's an array in JavaScript, it should not be modified. To replicate the issue, I created a simple example: htt ...

The updating of input and output does not happen instantly; there is a delay before changes

Having an issue with updating input values in React. When using the setState method, the console log does not show the updated input value immediately. For instance, typing "a n" into the input only logs "a" after the second keystroke... Although I under ...

Adjust the jQuery.ScrollTo plugin to smoothly scroll an element to the middle of the page both vertically and horizontally, or towards the center as much as possible

Visit this link for more information Have you noticed that when scrolling to an element positioned to the left of your current scroll position, only half of the element is visible? It would be ideal if the entire element could be visible and even centere ...

Is it possible to reduce a field value in firestore after successfully submitting a form?

I have a variety of items retrieved from firestore: availability : true stocks: 100 item: item1 https://i.stack.imgur.com/hrfDu.png I am interested in reducing the stocks after submitting a form. I used the where() method to check if the selected item m ...

Problem with exporting data from the API to a JavaScript file in Excel format

Instead of receiving actual data in the response, I am getting a set of characters. However, everything works fine when I click on Download file in swagger. Can someone help me diagnose the issue? function downloadDocFile(data: Blob, ext = 'xlsx' ...

I am looking to generate div elements using JavaScript to avoid the tedious task of individually creating numerous divs

Instead of manually typing out multiple div tags in the HTML, I would like to dynamically generate them using JavaScript and display them on the page. Below is an attempt at achieving this, but it appears to not be functioning correctly. var arr = {}; f ...

retrieving the webpage's HTML content from the specified URL using AngularJS

Utilizing the $http.get('url') method to fetch the content located at the specified 'url'. Below is the HTML code present in the 'url': <html> <head></head> <body> <pre style = "word-wrap: break ...

Insert a page break after content for desktop browsers

Is it possible to control the display of sections on different screen sizes? I have a page that looks good on 15" laptops, but larger resolutions cause the next section to appear on the first screen. Is there a way to show the next section only on th ...

Vue/Vuex - using async dispatch for AJAX requests in multiple components

I am working with vuex and using a store module to load user lists in my app through ajax. After the list is loaded, it doesn't fetch again if it's already present in the vuex store. I have implemented this logic in the main application layout as ...

Is there a way to create a Captcha image from text using JavaScript in an HTML document?

As I work on creating a registration web page, ensuring security is key. That's why I'm looking for a way to generate captcha images for added protection. Any suggestions on how I can transform text into captcha images? ...

I have observed that the form on an ASP.NET MVC Partial View can only be submitted after pressing the Enter key twice on the

**** Update - This issue seems to be specific to MS Edge. It functions properly with just one Enter key press on Chrome and Firefox.** I encountered a strange problem where a form only gets submitted after pressing Enter key twice in a text box. The form ...

Tips for ensuring the drop down button remains selected

My goal is to keep the sorting drop-down button selected after clicking on it, instead of resetting back to "All". Below are my HTML, CSS, and jQuery code. You can view the functionality on my website here: jQuery/Javascript: $(document).ready(function($ ...

Tips for utilizing a function within a callback function using jQuery

When using jQuery's .load() to load HTML files into a parent webpage, I am interested in executing jQuery/JS from the parent page against the loaded HTML file. It seems like this can be achieved with a callback function. The jQuery I'm using is ...