Changes made in Vuex will not be saved until they are manually committed using developer tools

One of the modules in my Vuex store is called login.js and it looks like this:

import axios from "axios";
import router from "@/router";

axios.defaults.baseURL = process.env.VUE_APP_API_ENDPOINT;

const state = {
  access_token: localStorage.getItem("access_token") || null,
};

const getters = {
  loggedIn() {
    return (
      state.access_token != null && localStorage.getItem("access_token") != null
    );
  }
};

const mutations = {
  doLogin(state, response) {
    const token = response.authentication_data.access_token;
    localStorage.setItem("access_token", token);
    state.access_token = token;
    router.push("/admin");
  };

const actions = {
  async getToken({ commit }, userdata) {
    let email = userdata.email;
    let password = userdata.password;
    let remember_me = userdata.remember_me;

    await axios
      .post("auth/login", null, {
        params: {
          email,
          password,
          remember_me
        }
      })
      .then(response => {
        if (response.data.meta.status == "true") {
          commit("doLogin", response.data);
        } else {
          alert("wrong password");
        }
      })
      .catch(error => {
        alert(error);
      });
  };

export default {
  state,
  getters,
  actions,
  mutations
};

The code for login.vue:

  methods: {
    ...mapActions(["getToken"]),
    login() {
      const userdata = {
        email: this.email,
        password: this.password,
        remember_me: true
      };

      this.getToken(userdata);
    }
  }

The issue I'm facing is that the token gets set correctly the first time when logging in, but upon refreshing the browser, the access_token is lost.

When checked in the browser, it looks like this:

https://i.sstatic.net/Hh8HB.png

However, committing via dev tools works and keeps the state persistent.

I've looked at similar questions on SO but couldn't find a solution:

vuex commit does not commit to store

Vue2 + Vuex Commit Not Committing (without Vue devtools)

Vuex Mutation running, but component not updating until manual commit in vue dev tools

How can I ensure that the state.access_token remains persistent without losing its value upon page refresh?

Answer №1

It appears that your code is functioning correctly and Vuex is successfully storing your data in the store. However, the issue you are facing stems from the fact that by default, Vuex does not save this data to localStorage, which I assume is what you mean by "commit". Several commenters have suggested using a third-party package like Vuex-PersistedState, or alternatively, Vuex-Persist for better customization and Typescript support.

To integrate Vuex-PersistedState into your project, you will need to modify your Vuex initialization. Here is an example of how to do so:

import createPersistedState from 'vuex-persistedstate' // import the package

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

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

Guide on how to iterate through the list of users within the component

Hello, I'm fairly new to working with react and I've encountered a challenge regarding implementing a loop within this component to display a list of all users. Despite trying numerous approaches, I haven't been able to figure it out. colum ...

Issue encountered with mouse handling on SVG elements that overlap is not functioning as anticipated

I am working with multiple SVG path elements, each contained within a parent SVG element, structured like this: <svg class="connector" style="position:absolute;left:277.5px;top:65px" position="absolute" pointer-events:"none" version="1.1" xmlns="http:/ ...

Steps for saving both checked and unchecked checkbox values in Firebase

I have a set of objects that I am using as initial data in my Ionic 3 application: public interests = [ { name: 'Travel', checked: false }, { name: 'Animals', checked: false }, { name: 'Theatre', checked: false ...

Transmitting a sequence of JSON information from php to JavaScript,

I am struggling to fetch a series of JSON data from PHP to my JavaScript file. Initially, I have multiple JSON data stored in an array in PHP, and I am echoing each one by looping through the array in my JavaScript file. <?php $result = array('{ ...

Pattern to identify a JSON string with Regular Expressions

Currently, I am working on developing a JSON validator from the ground up and have hit a roadblock when it comes to the string component. My original plan was to create a regex pattern that aligns with the sequence specified on JSON.org: https://i.sstatic ...

Transforming jQuery Object into a String after making an AJAX request

If I were to submit a form with some text in the value of user_input, let's say "I am free," through AJAX, and it comes back to me as a string. Once it becomes an Object, how could I convert it back into a string format? Thanks, <!DOCTYPE HTML> ...

Trigger Element Upon Click

Forgive me in advance for the lack of quality in this question, but I'll proceed anyway: All I want is for an element to slide open when clicked with a mouse! That's all! More specifically, I am looking for a single menu item that, upon clickin ...

Show the chosen value from the dropdown menu on all JSP pages

I have a header.jsp file containing a dropdown box labeled "Role". This header.jsp is designed to be included in all other JSP files using a directive. Once a user logs in, they are directed to a homepage where they must select a value from the dropdown ...

Changing Vuex store state by using mapped actions within the render function of a Vue component

I have been working on a slider with a modal that should open when an image is clicked. The modal state is stored in my Vuex store, and I need to dispatch an action from the image tag within my render function. While following Vue documentation, I have at ...

Activating the spinning wheel page-loading indicator in the browser through Socket.IO

Currently, I am constructing a web application using Node.js along with Socket.IO for managing data transfer between the client and server components. The central component of my web app is a content feed. To fetch the contents of the newsfeed, my client- ...

Executing a request via ajax using a radio button

Here is the input that I am working with: <input id="offline-42" onclick="javascript:checkoutSwitch(false);controlDivPayment('42');" name="payment" type="radio" value="offline-42" /> I am attempting to use ajax to add a product to the sh ...

Flask Server produces a response with a considerable delay when accessed through AJAX

I am currently running 2 servers on localhost, each with different ports. One of them is a basic flask server in Python and its code is provided below: from flask import Flask,jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) @app.rout ...

I am facing difficulties installing packages such as react-bootstrap on my dashboard

Encountering an issue with installing packages in my dashboard. For example, attempting to install react-bootstrap results in the following error: node version: 12.16.1 npm version: 6.13.4 gyp ERR! UNCAUGHT EXCEPTION gyp ERR! stack Error: Cannot find mo ...

Encountering a sudden problem while running gulp build due to a node_module - Surprising occurrence of Unexpected

Encountering an unexpected issue while running a gulp build process for a web app that I am struggling to resolve. The problem did not exist on the evening of 25/01/2019, but when attempting to execute the gulp build process this morning (30/01/2019), an ...

What is the best way to make an image expand when clicked, align it in the center of the webpage, and have it return to its original position with just one more click by utilizing

Currently, this is the code I am working with. The JavaScript functionality is working well, however, there seems to be an issue where the image does not return to its original size on a second click. Additionally, I am having trouble getting the CSS to ce ...

Bidirectional Data Binding in AngularJS

In my angular application, there is a dropdown with various values. When a user selects a specific value from the dropdown, I want to display the complete array corresponding to that value. <!doctype html> <html lang="en"> <head> < ...

AngularJS Skype URI Button Problem

Implementing a Skype button in my project using AngularJS has been challenging. Here is the code I am currently working with: HTML: <script type="text/javascript" src="http://www.skypeassets.com/i/scom/js/skype-uri.js"></script> <skype-ui ...

Vue: updating the :root CSS variable for a child component leads to an error - TypeError: Unable to access properties of undefined (reading 'style')

Fiddle: https://codesandbox.io/s/hardcore-mestorf-w1lsob?file=/src/App.vue In my project, I have created two simple files that are responsible for displaying a circle on the screen: https://i.stack.imgur.com/0ddI3.png The goal is to modify the circular ...

"Utilizing the power of ng-click to target specific child

I am facing an issue with my owl carousel where events are not firing on cloned items. In search of a solution, I came across a suggestion from Stack Overflow to move the event handler from the direct target to its parent element: Original code snippet: ...

What is the best way to showcase content using Chakra-ui SideBar in a React Application?

After exporting the SideBar, I imported it into my App.jsx SideBar.jsx 'use client' import { IconButton, Avatar, Box, CloseButton, Flex, HStack, VStack, Icon, useColorModeValue, Text, Drawer, Draw ...