Retrieving information stored in local storage from a different path using Vuex

Using the config panel route, I am fetching data and setting it to local storage using Vuex and StoreJS:

     const state = {
      message: [],
      // console.log(message);
      sec: 0,
      // other state
    };
    const getters = {
      message: (state) => {
        // console.log(this.state.message);
    
        return state.message;
      },
    
      sec: (state) => {
        return state.sec;
      },
      // other getters
    };
    
    const actions = {
      setMessage: ({ commit, state }, inputs) => {
        commit(
          'SET_MESSAGE',
          inputs.map((input) => input.message)
        );
    
        return state.message;
      },

  setSec: ({ commit, state }, newSecVal) => {
    commit('SET_TIMEOUT', newSecVal);
    return state.sec;
  },
  // other actions
};
const mutations = {
  SET_MESSAGE: (state, newValue) => {
    state.message = newValue;
    localStorage.setItem('message', JSON.stringify(newValue));  
  },
  SET_TIMEOUT: (state, newSecVal) => {
    state.sec = newSecVal;
    localStorage.setItem('sec', JSON.stringify(newSecVal)); 
  },
  // other mutations
};

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

To display this data on the home route, you can access it in the following way:

Retrieving regular state data using MapGetters and implementing it as follows:

computed: {
   

    ...mapGetters({
      message: "message",
      sec: "sec"
    }),

If there is no data available, how do I automatically fetch it from local storage when the page reloads?

This is what my mounted function looks like:

mounted() {
    this.$store.dispatch("SET_MESSAGE");
    this.$store.dispatch("SET_SEC");    
  },

Answer №1

For seamless synchronization between your state and local storage, I recommend utilizing the package vuex-persistedstate.

Another approach is to define your state as shown below.

const state = {
  message: localStorage.getItem('message') || [],
  // console.log(message);
  sec: localStorage.getItem('sec') || '',
  // other state
};

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 component encounters a transformation in which prop values shift to undefined

My component seems to be encountering some instability. The value assigned to "this.state.list" from this.props is being immediately set to "undefined". I'm struggling to comprehend why this is happening. Can anyone spot the issue in the code? this.s ...

Is it possible to create a single Vue component with different sections that can be routed to using buttons from another component?

As a newcomer to Vuejs, I am aiming to optimize my code by consolidating it into one Vue component and specifying routing just once. Currently, I have an info.vue in the apps directory and prises.vue & priseshigh.vue in another directory. My goal is to onl ...

Tips for smoothly applying a class to an image for seamless transitions, avoiding any awkward clunkiness

Check out my work on jsfiddle I understand that the image may not be visible, but I'll do my best to describe it. The header smoothly animates as I scroll down, but the image abruptly changes size instead of smoothly resizing. I want it to gradually ...

Exploring the benefits of utilizing useState and localStorage in Next.js with server-side

Encountering an error consistently in the code snippet below: "localstorage is not defined" It seems like this issue arises because next.js attempts to render the page on the server. I made an attempt to place the const [advancedMode, setAdvanced ...

Using Node.js await function results in an undefined response

One issue arises when a POST call is made to /login; the const user variable ends up being assigned as undefined even though getUser() consistently returns the expected value. Interestingly, the call console.log(getUser()); located at the end of the file e ...

Does this function only function on a singular div?

I need some help! I'm having trouble getting a function to trigger on the divs below the initial one. Any advice? ...

In TypeScript, use a Record<string, any> to convert to {name: string}

I have developed a custom react hook to handle API calls: const useFetch: (string) => Record<string, any> | null = (path: string) => { const [data, setData] = useState<Record<string, any> | null>(null); var requestOptions: Requ ...

modify the color of a box within a grid upon clicking it

I am curious if it is possible to change the color of a box when it is clicked. I am working on coding a "calculator layout" and would like to start with this part 1 2 3 4 5 6 7 8 9 0 This is what I have been working on and struggling with. $(docume ...

exciting command: templateUrl

I am in need of assistance with a particular issue: I am trying to configure settings for an application and would like to utilize the UI-Bootstrap accordion. This is the HTML code I have so far: <accordion close-others="oneAtATime"> <accor ...

Can one manipulate the simulation to make isTrusted=true a reality?

Is there a way to simulate an isTrusted=true in touchStart event triggering? Are there any libraries or workarounds that can make this achievable? When I run the touchStart event programmatically versus physically triggering it, the output differs. Below ...

Guide on transferring morph targets from Blender to three.js?

Is there a way to export morph targets from a Blender file to three.js? I'm aiming to create a json file containing an array called "morphTargets." Any advice on how to achieve this? ...

I would like to find the difference between two arrays by creating a third array that only contains the elements not found in the first array

Subtracting elements from two arrays. arr1=["AT","IN","UK","US"] and arr2=["UK","ZA"]. I want the result to be arr1-arr2 = ["AT","IN","US"] I have attempted to perform the subtraction of the arrays as described above, but instead of obtaining the correct ...

Separate modules in the Webpack.mix.js file don't produce any output files in the public folder

I've recently been tackling a Laravel project with an extensive webpack.mix.js file residing in the root directory, boasting nearly 5000 lines of code. In an effort to enhance organization and maintainability, I've opted to break it down into ind ...

Issues with Bootstrap-slider.js functionality

I'm having trouble getting the bootstrap-slider.js library from to function correctly. All I see are textboxes instead of the slider components. You can view an example at I have verified that the CSS and JS files are pointing to the correct direc ...

Having trouble uploading an image to AWS using Angular and NodeJS?

I am currently working on a Node/Express application and I need to gather file information for uploading from an Angular/Ionic front end. To achieve this, I have created a separate Service in Angular that successfully retrieves the Image name. However, my ...

Eliminate unnecessary spaces in Vue with Moment

Utilizing moment in this way: pages/index.vue <template> <div class="box"> {{ item.updateDate | moment("from", "now") }} </div> </template> An illustration of item.updateDate would be 1580564625000. I'm empl ...

What is the best way to display a nested JSON object structure?

{ "Title": "Jurassic Park", "Year": "1993", "Rated": "PG-13", "Released": "11 Jun 1993", "Runtime": "127 min", "Genre": "Action, Adventure, Sci-Fi", "Director": "Steven Spielberg", "Writer": "Michael Crichton, David Koepp", "Actors": "Sam ...

What are the steps to update the title and creator details in the package.json file of an Openshift Node.js application?

Recently delving into the world of node.js and PaaS platforms like Openshift, I find myself faced with a perplexing issue. How exactly can I modify the values generated by Openshift in the package.json file without encountering any errors? Each time I at ...

What is the best way to retrieve the value of a checkbox element in React.js when submitting a form?

Whenever I try to submit a form, I encounter an issue where I am unable to retrieve the value of the checked boxes (I don't mean the check value but the actual value attribute of the HTML element). Here is an example of my element in the parent compo ...

What is the process of sending an HTTP/HTTPS request from a Node.js server?

Currently diving into the world of Node.js, I am experimenting with using a Node.js Application on cPanel to generate a JSON response upon accessing its URL. Upon visiting the app's URL, it seems that the Node.js server is functioning correctly. Afte ...