Persist state in Vue by using the `vue-persistedstate` reducer

Currently, I am utilizing vue-persistedstate with specific modules that are set to be persisted using the path attribute. This setup is functioning smoothly.

However, I encountered an issue when attempting to combine it with the reducer. In this scenario, the modules specified in the path no longer persist, and all modules end up being persisted by the reducer instead. How can I properly configure the reducer to only persist the modules listed in the path?

const persistedstate = new createPersistedState({
  key: "newsportal-vuex",
  storage: window.localStorage, 
  paths: ["auth", "venues", "play", "playWS", "purchaseSettings"], // only the persisted ones
  reducer(val) {
    if (!localStorage.getItem("newsportal_isuseracceptcookie")) {
      // DO NOT PERSIST STATE IF USER DECLINES COOKIES
      return {};
    }
    return val; // <-this returns ALL MODULES. I want to only include modules from the specified paths
  }
});

Thank you in advance for any assistance provided.

Answer №1

just had a realization that I should rebuild the object

transform(val, paths) {
    if (!localStorage.getItem("newsportal_isuseracceptcookie")) {
      // do not use persistedstate if user declines cookies
      return {};
    }

    // create transformed state based on specified paths
    let transformer = {};

    Object.entries(val).forEach(entry => {
        const [key, value] = entry;
        if (paths.includes(key)) {
            transformer[key] = value;
        }
    });

    return transformer;
}

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

Creating a new buffer by extracting a segment of another buffer in Node.js

Currently, I am executing an AWS call in Node.js that returns a buffer. var aws = new AWS.S3(); var params = { Bucket: s3config.bucket, Key: s3config.tile_directory + filepath //, // Range: 'bytes=0-' + (this.HEADER_SIZE - 1) }; ...

Using AngularJS to update attributes in an HTML tag within a string

My string contains HTML tags : var str = "<div><p></p><p><i>blabla</i></p><p><i><b>blaaaaaablaaaaa</b></i></p><iframe src='urlAAA' height='400' width=&ap ...

Tips for accessing a variable value within a JavaScript function

I am currently facing an issue where I am unable to retrieve a variable from a JavaScript function and use it outside of the function. While I can successfully output the variable value inside the function, I am struggling to access it elsewhere in my sc ...

Execute the npm command to organize the files in case the specified directory does

I am facing an issue with my npm package.json script that needs to be executed only when the dist folder is not present. Here is the snippet from my package.json: "scripts": { "predev": "! test dist && webpack --config=webpack.dll.config.js } ...

Reversing the order of input-group-addon and input in bootstrap on mobile devices

I attempted to adjust the layout of a bootstrap input-group-addon on mobile devices by using two input elements and manipulating their display and visibility properties. From a design standpoint, I achieved the desired result as the input is now positione ...

failure of svg spinning

I'm currently working with an SVG file and attempting to incorporate a spinning animation similar to loaders and spinners. However, I am facing an issue where the rotating radius is too large and I am struggling to control it effectively. CSS: .image ...

Transfer Data from a Factory to a Controller in AngularJS

Although it may seem like a simple question, it has taken me nearly 3 hours to try and figure out what went wrong here. Perhaps someone could help identify the issue and provide a solution (it seems like an easy fix, but I'm just not seeing it). So, h ...

Determining when a text area has selected text without constant checking

class MarkdownEditor extends React.Component { constructor(props) { super(props); this.timer = null; this.startIndex = null; this.endIndex = null; } componentDidMount() { this.timer = setInterval(() => { this.setSelectio ...

Save the content of a string object into an array

I am currently implementing an array sorting functionality using the MVC approach. The array called "array" is used to store values provided at runtime. Within the view, there is a textbox and a button for user input of integer values. Upon clicking the bu ...

I'm receiving a TypeError in Nodejs indicating that the hashPassword function is not recognized as a function. Can anyone offer advice on how to

How's everything going? I could really use your assistance! I'm currently working on developing an API for registering authenticated users, with data storage in the MongoDB Atlas database (cloud). Unfortunately, I've run into a troubling er ...

The behavior of Elementor lightbox buttons upon being clicked

When using Android, I've noticed that the lightbox briefly displays a semitransparent cyan bar on the left and right buttons when they are pressed. Is there a way to control or prevent this behavior? Any suggestions would be appreciated! Thanks in adv ...

Unable to render chart using angularjs-nvd3-directives

After developing a basic Angular - nvd3 project, I decided to utilize liveData.example from the angularjs-nvd3-directives Library on Github. To tailor it for my needs, I made enhancements to integrate with my REST API. Here is the REST API endpoint: http ...

Issue: Attempting to access the `userName` property on an undefined object (`tem`), resulting in a TypeError while using flalist

A concern has arisen with the React Native Flatlist as it fails to render properly. What steps should be taken in this scenario? Below is the code snippet for reference: Image description available here import React, {useState, useEffect} from 'react ...

Streamline a javascript code with numerous elements

Seeking assistance in simplifying this code Currently, I find myself constantly updating this code each time a new entry is uploaded. I am looking for a solution where there is a single script that can identify the element IDs ("#rolly" or "#lagrimas") a ...

Hover over the sprites using the "spritely" plugin to see the magic unfold

I'm looking to initiate an animation when the mouse hovers over a sprite and have it stop when the mouse moves away. After exploring various solutions, I found one that seemed promising: Why does jQuery spritely animation play an extra frame on secon ...

random mongoose response 500

I came across a nodeJS code recently that was supposed to retrieve random documents from my mongoose collection using the mongoose-random plugin. However, whenever I call the findRandom() method, it returns a 500 error. test.js Below is the code snippet: ...

Is there a way to adjust the font size in Javascript/Html without changing the color?

I have a code snippet that creates a button to increment a variable, and I want to change the font size of the displayed variable. This code is for a game akin to cookie clicker. <div class="game-object"> <script type="text/javascript>"; var c ...

A step-by-step guide on creating a route in vue.js

As a newcomer to the world of javascript and vue.js, I have encountered an issue while attempting to incorporate a new route into an existing program. I decided to create my new component in a distinct file named Miniature.vue Here is how I added the new ...

How to use jQuery to extract a particular text from an anchor tag

If I want to choose a specific anchor text and make changes to it, I can do so by targeting anchors with a certain href attribute. For example, on a page with multiple unordered lists, each containing different links: <ul> <li><a href="v ...

When using Bcrypt compare(), the result is consistently incorrect

After implementing this code for comparison, I encountered an issue with the compare password functionality. UserSchema.pre('save', async function() { const salt = await bcrypt.genSalt(10) this.password = await bcrypt.hash(this.password, ...