Avoid getting the application stuck by handling persistent state in VueX

I've been using the vuex-persistedstate module to handle state management and store it in localStorage. However, whenever there's an update to the data, the app freezes due to the amount of state that needs to be saved.

To address this issue, I'm attempting to implement a promise that allows for business calculations to take place while the string is being generated. Once the string is prepared, it should then be stored in localStorage.

This is the approach I'm currently testing:

const buildLocalStorageString = async (state) => {
  return await JSON.stringify(state);
}

export default new Vuex.Store({
  state: { etc, etc, etc },

  plugins: [createPersistedState({
    key: 'myApp',
    setState (key, state, storage) {
      buildLocalStorageString(state).then(string => {
        storage.setItem(key, string) 
      }) 
    }
  })],
})

Despite these efforts, the problem remains unresolved. There's still a noticeable lag whenever the app undergoes updates.

Answer №1

It has been noted that all localStorage calls operate synchronously, and due to Javascript's single-threaded nature, saving a large chunk of data into local storage will inevitably block all other executions.

To address this issue, I propose a solution of dividing the data and storing it in local storage separately. This can be achieved by utilizing multiple createPersistedState functions.

Here is a very basic example implementation:

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

Vue.use(Vuex)

const moduleA = {
    state: {
        a: 'a'
    },
    mutations: {
        updateA(state) {
            state.a += 'a';
        }
    }
}

const moduleB = {
    state: {
        b: 'b'
    }
}

export default new Vuex.Store({
    modules: {
        moduleA: moduleA,
        moduleB: moduleB
    },
    plugins: [createPersistedState({
        key: 'vuex_a',
        paths: ['moduleA']
    }), createPersistedState({
        key: 'vuex_b',
        paths: ['moduleB']
    })]
})

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

Utilize Vue CLI 3 to enable popups in arcgis API JS

I've been attempting to enable popups from the ArcGIS API JS to show using the Vue-CLI 3 framework. Unfortunately, even with a simple sample code, I'm unable to make it function properly. Below is the code initially written in vanilla JS: <!DO ...

Exceeded Limit: Google Maps API cannot process more than 10 destinations at this time

After spending the entire day researching, I am still unable to find a solution that solves my issue. I am utilizing the Google Maps Distance Matrix Service with 1 origin and 14 destinations. While testing the modified sample code from Google (https://deve ...

creating a Vue app using Node results in an HTML page with no content due to syntax errors

After creating a VueJs page using the CLI, I wanted to share it with others who might not have Vue CLI or Node installed. Just like opening .html files in a browser, I tried to open the index.html file after building it. However, when I opened the file, a ...

Interact with a JSON API using JavaScript by incorporating dynamic user input

Recently, I delved into tutorials on utilizing JSON data and JavaScript. Feeling inspired, I decided to create a simple app using an API. However, I encountered a hurdle and I'm struggling to identify its cause. The problem seems to be related to how ...

Generate a fresh array using the data from the existing array object

I have nested objects within arrays that I need to manipulate. { "page": [ { "num": "1", "comp": [ { "foo": "bar", "bar": "foo", ...

Having trouble initiating the webpack development server

As a newcomer to ES6, I decided to set up my development environment by following a guide for beginners. After completing all the steps as instructed, I reached the point of installing the webpack development server. Upon entering the command npm run bui ...

The Battle of Brainpower: Smarty vs. JavaScript/AJAX

One question I have is: Is there a specific guideline or convention for determining when to use "Smarty templating" versus using JavaScript Ajax calls to generate content? I have the ability to generate content dynamically using Ajax/JavaScript calls. Whi ...

Is it possible to utilize gulp to eliminate all require.js define([...]) wrappers throughout the codebase?

Is it possible to test my app without using require.js in order to assess the performance and file size if all files were concatenated into a single one? I'm contemplating using gulp to gather all *.js files in the app, running a gulp-replace to elim ...

Automated submission feature for Angular scanning technology

As a newcomer to angular.js, I am dedicated to learning the ins and outs of the framework. Recently, I created a form that enables me to search using a barcode scanner, followed by pressing a submit button. However, I find this process redundant as I wou ...

Instructions for securing a React Front End with Node.js Express-Sessions authentication:

I have decided to move away from using Firestore auth in order to develop my own authentication system. Here is my goal: To create a React web app that allows users to sign up and sign in. Authenticated users should be able to interact with a REST API, w ...

Switch the designation to Hover Class

I am working with nested divs and have assigned a CSS class to one of the inner divs. How can I trigger the hover effect of the class (class.hover) when the user hovers over the outer div, even if they are not directly over the inner div? I believe this m ...

Creating an HTML element within a three.js globe

I have a globe created using three.js Reference: I am trying to display an HTML div at a specific latitude/longitude on the globe. Can someone guide me on how to position the div at a particular lat/long? What I've attempted: I'm currently stu ...

Tips for Angular4: ensuring ngOnDestroy completion before navigation

My task involves managing a list of objects where the user can choose an object to edit using a child component. However, when the user returns to the list component, the child component needs to clean up in the ngOnDestroy method, which includes making a ...

Unable to access $_POST parameters in PHP when making an Ajax request

My HTML file is shown below: <script> var xml = new XMLHttpRequest(); xml.onreadystatechange = function(){ if (xml.readyState === 4 && xml.status === 200) { console.log(xml.responseText); } } xml ...

Javascript continuously swaps out text from distinct strings in a loop

I wrote a loop to split a string and search for certain text to replace it with another string. Here is an example of what I have done: function replaceStr(str, find, replace) { for (var i = 0; i < find.length; i++) { str = str.replace(new RegE ...

Switching to '@mui/material' results in the components failing to render

I have a JavaScript file (react) that is structured like this: import { Grid, TextField, makeStyles } from '@material-ui/core' import React from 'react' import {useState} from 'react' //remove this function and refresh. see ...

What causes the statement to be executed before the database transaction?

How can I ensure that the state domains are set only after all DB transactions are completed in my code? Please provide guidance on how to perform this operation correctly. I am using the following method to update the new domains array: setFavorites() { ...

Integrating AngularJS code into dynamically generated HTML using JavaScript

I am currently utilizing an outdated version of AngularJS (1.3). I have a page where I need to dynamically display different content based on database values. If the user interacts with the page and changes the database value, I want the displayed content ...

Employing Visual Composer within WordPress has resulted in the raw JavaScript not being properly applied to my raw HTML code

Sharing some code that functions properly in my browser and I want to implement on my WordPress page: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8> <!-- Getting jQuery --> <script src="http://ajax.goog ...

Is there a way to determine the distance in miles and feet between various sets of latitude and longitude coordinates?

I am working with an array of latitude and longitude coordinates and I am looking to use JavaScript or Typescript to calculate the distance in miles and feet between these points. const latsLngs = [ { lat: 40.78340415946297, lng: -73.971427388 ...