What is the best way to store specific data in localStorage in a Nuxt.js application?

I have a situation where I want to persist only the user data in my store, which is stored in a nuxt.js store. Currently, all data in the store is being persisted in localStorage. Here is my implementation in store/login.js.

export const state = () => ({
    user: ''
})

export const mutations = {
    setUser(state, newUser) {
        state.user = newUser;
    }
}

export const getters = {
    getUser(state) {
        return state.user
    }
}

To achieve this, I am utilizing the vuex-persist plugin for data persistence. Below is the setup in plugin/vuex-persist:

import VuexPersistence from 'vuex-persist';

export default ({ store }) => {
  new VuexPersistence({
    key: 'vuex',
    storage: window.localStorage,
  }).plugin(store);
}

Your assistance on this matter is greatly appreciated!

Answer №1

According to the vuex-persist documentation:

const vuexCookie = new VuexPersistence<State, Payload>({
  restoreState: (key, storage) => Cookies.getJSON(key),
  saveState: (key, state, storage) =>
    Cookies.set(key, state, {
      expires: 3
    }),
  modules: ['user'], //serialize only the user module
  filter: (mutation) => mutation.type == 'logIn' || mutation.type == 'logOut'
})

The options object contains a key named "modules" which should have a value of string[] type, representing the names of the modules you WANT to serialize.

Constructor parameter: modules
Value type: string[]
Description: Specify the list of modules that should be persisted. (Avoid creating your own reducer if using this option)

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 sets $vm.user apart from $vm.$data.user in Vuejs?

When you need to retrieve component data, there are two ways to do so: $vm.user and $vm.$data.user. Both methods achieve the same result in terms of setting and retrieving data. However, the question arises as to why there are two separate ways to access ...

Transmitting a JSON object and a file simultaneously via FormData in an AJAX request, then retrieving the JSON object in PHP

I need assistance with sending a JSON object along with a file in an AJAX call. Here is my current setup: Javascript $('#btn').on('click', function(){ var file_data = $('#imgFile').prop('files')[0]; var for ...

Dealing with Ajax errors in Django reponses

My code includes an ajax call to a Django view method: $("#formi").submit(function(event){ event.preventDefault(); var data = new FormData($('form').get(0)); $.ajax({ type:"POST", url ...

Can someone explain the significance of receiving a TypeError when trying to access properties of null (specifically 'useRef') in a React application?

I encountered an issue while working on a React project...the browser console displays the following error. What does this mean? And how can I resolve it? react.development.js:1545 Uncaught TypeError: Cannot read properties of null (reading 'useRef ...

Transformed an array of objects by extracting values from a specified object using TS/JS

Hey folks, I'm wondering what's the most effective way to update an array of objects with values from another object. For example, imagine we have an array and an object structured like this: let arr = [ { parameter: 'aaa', ...

Node.js and socket.io come together in this collaborative text editing tool

I'm currently working on a collaborative app utilizing node and sockets that includes a simple text tool feature. My goal is for any user who types and applies text to the canvas to have that text visible to all other connected users. Here's wha ...

Ways To Create Multiple HTML Players

After successfully creating an audio player with html, css and javascript, I now face the challenge of adding multiple players to a single page. However, when attempting to play any player besides the first one, it only plays the initial player. How can ...

Does anyone know of a nodemon alternative that works on Windows?

Is there a Windows-compatible service similar to nodemon that can assist with Nodejs development now that it's available on the Windows platform? ...

Unable to eliminate the dependency in the Vue project

After incorporating the vue horizontal list dependency in my project, I am facing challenges with removing it. Despite numerous attempts to uninstall using "npm uninstall vue-horizontal-list" and variations like global and --save options, the dependency re ...

Issue with Promise function not resolving in the context of javascript and Wit.ai

Currently, I am in the process of updating the functions in my messenger/wit.ai chat bot to transition from using callbacks to promises. The initial format functions properly: ['buildScenario'](sessionId, context, cb) { var trendChoice = s ...

Incorporating JavaScript: Demonstrating content on button click based on pattern matching

I want to display content in a div when the user clicks on a button. There are three buttons: test connection src, test connection dest, and next. When I click on the test connection src button and there is no input, it should display a message. However, ...

Is today within the current week? Utilizing Moment JS for time tracking

There is a problem that I am facing. Can you assist me in determining whether the day falls within the current week? I am currently developing a weather forecast service and need to validate if a given day is within the current week. The only clue I have ...

Adding dynamic attributes like pattern and title to input controls

I currently have an HTML input field that looks like this: <input type="text" value="<%= this.CustomerAcctNumber %>" name="CustomerAcctNumber" id="CustomerAcctNumber" maxlength="19" onkeyup="CustomerAcctNumberChange()" required > Upon loading ...

The request cannot be processed due to Error 405: Method not permitted

I am trying to send my json data to a specific URL or update the json data on one of my site URLs, but I am encountering a 405 error. Here is the code snippet that I am using. $.post("details", {name: "John", location: "us"}); ...

Loading images onto tinyMCE

I’m currently creating a website using AngularJS, NodeJS, mongoose, mongoDB, and other technologies. On this site, I have integrated a tinyMCE text editor. However, I am now looking for a way to include images in the editor. I have explored solutions lik ...

Complete the modal window form

I'm currently facing an issue with populating a modal window form. To provide some context, when I click on a grid row to edit a user, I make an ajax call which fetches specific data related to that user. Here is the existing code snippet: <modal ...

Is there a more efficient method for transferring data between dynamically loaded components?

My recent project involved creating a small application using Vue.js and Express.js. To prepare the necessary components from the server, such as the combobox for Article.Category and Article.User, I needed to render options from the server. I utilized < ...

When the enter key is pressed in Spring and Vue.js, the request method 'POST' is not supported

One issue I am encountering is that when I click on the search button, everything works perfectly fine. However, if I try to press enter instead, an HttpRequestMethodNotSupportedException error is thrown. The strange thing is that I do not have a POST co ...

What is the process for accessing the value property within an array?

When parsing JSON recursively, I have encountered an issue with saving properties into separate arrays based on whether they belong to the "array" or "list". The goal is to extract the value of the "label" property and store it accordingly. Despite my atte ...

Refresh content on an HTML page using information retrieved from an external PHP post request

So, I have a problem with communication between my two web pages - mobile.html and video.php. The idea is for mobile.html to send an AJAX post request containing a single variable to video.php. Video.php should then read this variable and pass it to a Java ...