Persisted state in Vuex fails to retain data after the page is refreshed

I recently added persisted state to my Vue application using the command npm install --save vuex-persistedstate.

After that, I configured my Vuex store.js file in the following way:

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    title: ''
  },
  mutations: {},
  actions: {},
  getters: {},
  plugins: [createPersistedState()]
})

..In another component, I set the value for store.title like this:

this.$store.state.title = this.input

This approach has been effective so far.

However, when I refresh the page (using F5), the stored value from this.input no longer persists in this.$store.state.title, causing a malfunction in my website.

What could I be doing incorrectly?

UPDATE: I found an alternative solution without relying on the Vuex plugin:

First:

this.$store.state.title = this.input
localStorage.setItem('title', this.$store.state.title)

Then:

mounted () {
    this.$store.state.title = localStorage.getItem('title')
  }

I'm still curious about why the Vuex plugin is not functioning as expected :(

Answer №1

Could you please test out the following code snippet?

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    title: ''
  },
  mutations: {},
  actions: {},
  getters: {},
  plugins: [createPersistedState({
     key: 'keyname',
     storage: window.localStorage         
  })]
})

In the "createPersistedState" function, you also have the option to specify a path using 'paths: ['accessRights']' as an additional property. If no paths are provided, the entire state will be persisted.

Answer №2

If you are working with #vuex store modules, I found a solution for my #vue #vuex #laravel project to save the store state using #vuex-persistedstate. Remember to set secure to false if you are not using HTTPS.

import createPersistedState from 'vuex-persistedstate';
   import Cookies from 'js-cookie';
   Vue.use(Vuex);
   export default new Vuex.Store({
     strict:true,
   modules:{
    party,
    contract
    },
   plugins: [createPersistedState(
    {
        paths:['party.selectedParty','contract.contracts', 
   'contract.partyId', 
   'contract.partyContracts',
        'contract.selectedContract',

         ],
        storage: {
            getItem: key => Cookies.get(key),
            setItem: (key, value) => Cookies.set(key, value, { expires: 3, 
         secure: false }),
            removeItem: key => Cookies.remove(key)
          },

    }
       )],
   });

Answer №3

There are instances where the state in cookies is not updating for unknown reasons. One simple solution is to switch the storage method to localStorage by following these steps:

createPersistedState({
    key: 'somekey',
    storage: window.localStorage,
    // getState: (key) => Cookies.getJSON(key),
    // setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: true })
})

Answer №4

I encountered a similar issue with this particular extension, but upon closer inspection, I realized that the root cause wasn't due to my improper use of Vuex. Initially, I was changing state values directly using this.$storage.state.VARIABLENAME, which proved to be incorrect. After revisiting the Vuex documentation, I discovered that accessing state values through mutations was the correct approach. Once I made this adjustment, the extension functioned as intended.

To update state values properly, follow these steps:

context.commit("SET_VARIABLENAME","value")

Your mutations in the Vuex store should resemble the following structure:

mutations: {
   
    SET_VARIABLENAME(state,status){
      state.MYVARIABLE = status
    },

And within the state block of your Vuex setup:

state: {
    MYVARIABLE: null,
}

Answer №5

It seems that the issue arises only when a commit call is made:

Your index.js file:

import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    count: 0
  },
  plugins: [createPersistedState()],
  mutations: {
    increment: state => state.count++,
    decrement: state => state.count--
  }
});

new Vue({
  el: "#app",
  computed: {
    count() {
      return store.state.count;
    }
  },
  methods: {
    assign() {
      store.state.count = 4;
    },
    increment() {
      store.commit("increment");
    },
    decrement() {
      store.commit("decrement");
    }
  }
});

Index.html content:

<div id="app">
  <p>{{ count }}</p>
  <p>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
  </p>
  <p>
    <button @click="assign">Assign 4</button>
  </p>
  <small>
    Go to your localStorage to view the changes.
  </small>
</div>

Details in package.json file:

{
  "name": "vuex-persistedstate",
  "version": "1.0.0",
  "description": "A simple demonstration of the vuex-persistedstate plugin",
  "keywords": ["vue", "vuex", "vuex-persistedstate"],
  "main": "index.js",
  "dependencies": {
    "vue": "2.5.22",
    "vuex": "3.1.0",
    "vuex-persistedstate": "2.5.4"
  }
}

Explore the code in CodeSandbox with dark theme and font size 14.

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

What is the origin of this MouseEvent attribute?

In my jsfiddle project, there is a white square that can be moved around by the mouse. When the mouse button is released, it displays the x and y coordinates of the square. To see the project in action, visit: http://jsfiddle.net/35z4J/115/ One part of t ...

Encountered a problem while trying to set up the Angular Material Library that has been cloned from

Trying to setup a library that has been forked from https://github.com/angular/material2. git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="63040a1723040a170b16014d000c0e">[email protected]</a>:vugar005/m ...

How can AngularJS service methods be assigned to controller $scope for use in an ng-repeat loop in the view?

As part of my development process, I decided to refactor my controller code in order to make it more reusable across multiple controllers. The original version of the controller (colorController.js) worked perfectly fine before I attempted to refactor it i ...

Implement a versatile Bootstrap 5 carousel featuring numerous sliders

Is it possible to create a Bootstrap 5 carousel with six items displaying at a time instead of three? I tried changing the value in the JS code, but it didn't work. Can you correct my code so that it displays six items at a time and can be variable la ...

TS: How can we determine the type of the returned object based on the argument property?

Assume we have the following data types type ALL = 'AA' | 'BB' | 'CC'; type AA = { a: number; }; type BB = { b: string; }; type CC = { c: boolean; }; type MyArg = { type: ALL }; I attempted to create a mapping between type n ...

The React project successfully compiled, but it is not displaying in the browser

I have completed several react projects in the past, but this is the first time I have run into this issue. After following the steps: npx create-react-app myapp cd myapp I successfully created the react project and ran: npm start Everything seemed to ...

Encountering an issue with NPM while running `npm install` resulting in the error message: 'npm ERR! Maximum call stack size exceeded'

As I work on a modified version of the popular wordpress plugin Sensei-lms, I encountered some challenges. The plugin developers have provided guidelines for setting up a development environment which can be found here. After following the instructions an ...

Typescript issues arise when a library lacks any available types for download

I attempted to incorporate the react-keydown library into my project, but encountered the following error: Could not find a declaration file for module 'react-keydown'. '/home/path../node_modules/react-keydown/dist/index.js' implicitl ...

implementing a delay after hovering over a CSS hover effect before activating it

I'm trying to achieve a specific effect using JavaScript or jQuery, but I'm struggling to figure it out. I have created a simple CSS box with a hover effect that changes the color. What I want is for the hover effect to persist for a set amount o ...

Using JavaScript regex to substitute white spaces and other characters

Here is a string I need to modify: "Gem. Buitentemperatuur (etmaal)" I want to remove all spaces, capital letters, and special characters from the string so that it becomes: "gem_buitentemperatuur_etmaal" ...

Adjust the child content within a React component based on the element's width, rather than the overall window size, by implementing dynamic resizing without fixed breakpoints

I am working with a react component that displays a div containing menu items which are aligned horizontally using inline-block. The menu items have text labels "Toy Store", "Configure your Toy", and "About Us". My challenge is to dynamically change the ...

Exploring the contrast between dependencies and devDependencies in NPM 5

The question below pertains to a project that I am not planning to publish on any package manager such as npm. When using NPM 3, running shrinkwrap without the --development flag would exclude packages listed in devDependencies from npm-shrinkwrap.json. ...

Is there a way to prevent Webpack file names from constantly changing?

I am completely new to using webpack and I'm trying to figure it out. Currently, I have set up a boilerplate template with vue-cli. When I run npm run build, my files compile to the /dist/build folder and are then split into separate js and css folde ...

Node-pty in NWjs application causing DLL malfunction

When attempting to run a terminal emulator / command prompt in NW.js using xterm JS and node-pty, I encountered a DLL Error. The following is the log: Uncaught Error: A DLL Initialization Routine Failed. \\?\C:\Users\volke.a\ ...

Converting a CSV object into a JSON object using Node.js

I am attempting to transform a CSV object into a JSON object on a line-by-line basis. Converting the entire CSV file to JSON is not viable for me as it contains over 4 million entries. While utilizing the csvjson module, it seems that converting a CSV obj ...

Run the npm build command to create two different builds

I have three files: core1.js, core2.js, and wrapper.js. How can I configure NPM to create two different outputs: core.js containing core1 and core2 all.js containing everything I want to publish all.js for the public, while core.js is intended for in ...

Show or hide text when list item is clicked

This is the rundown of services <div> <a href="#hig"><button class="tag-btn">High blood pressure Diabetes</button></a> <a href="#hih"><button class="tag-btn">High ch ...

Issue with jQuery ajax in Internet Explorer 6

Hey there, I'm dealing with a strange issue: The success handler in my $.ajax call looks like this: function(data){ alert(data); } Seems pretty straightforward, right? The problem I'm facing is that the data sent by the server is ALW ...

Printing a React component using a button causes formatting related to className to be lost, while printing it inline preserves the formatting

I've hit a roadblock in trying to figure out the React and printing issue for the past week and a half, and it feels like I'm going in circles. Despite finding some helpful solutions on Stack Overflow, none of them seem to work completely for me ...

Execute npm commands within a cmake project

I have a complex C++ project and I recently added a C++ Node.js addon to it using CMake. I want to build this addon along with my entire project, so I need to make modifications to the cmake file accordingly. In the root cmake file, I made the following c ...