What is the process of creating a deep clone of the state and reverting back in Vuex?

Looking to create a snapshot or clone of an object property within the Vuex tree, make modifications, and have the option to revert back to the original snapshot.

Context:
In an application, users can test out changes before confirming them. Once confirmed, these changes should reflect in the main Vuex tree. Users also have the option to cancel the changes and return to the previous state.

Example:

state: {
  tryout: {},
  animals: [
    dogs: [
      { breed: 'poodle' },
      { breed: 'dachshund' },
    ]
  ]
}

User enters "Try out" mode and changes one breed from poodle to chihuahua. They then decide whether to discard or apply the changes.

state: {
  animals: [
    dogs: [
      { breed: 'poodle' },
      { breed: 'dachshund' },
    ]
  ],
  tryout: {
    animals: [
      dogs: [
        { breed: 'chihuahua' },
        { breed: 'dachshund' },
      ]
    ]
  }
}

Discard (reverts to the previous state):

state: {
  animals: [
    dogs: [
      { breed: 'poodle' },
      { breed: 'dachshund' },
    ]
  ],
  tryout: {}
}

Apply (saves the changes in the main Vuex tree):

state: {
  animals: [
    dogs: [
      { breed: 'chihuahua' },
      { breed: 'dachshund' },
    ]
  ],
  tryout: {}
}

What are some effective methods to deep clone a state, make alterations on the clone, and later choose between discarding or applying those changes? This example is simplistic, but the solution should be applicable to more intricate objects or trees.

Edit 1:
There exists a library named vuex-undo-redo, which logs mutations but has certain limitations. Another discussion on Stack Overflow titled Going back to States like Undo Redo on Vue.js vuex suggests using the vuex function replaceState(state).

Answer №1

To achieve state management with vuex, you can utilize the combination of JSON.stringify, JSON.parse, and replaceState.

Here's an example implementation:

const storedStates = [];

// Save the current state
storedStates.push(JSON.stringify(state));

// Retrieve a state from the stack
if (storedStates.length > 0) {
  this.replaceState(JSON.parse(storedStates.pop()));
}

Additionally, you can also work with specific parts of the store:

const animalStates = [];

// Save the animals state
animalStates.push(JSON.stringify(state.animals));

// Reload the animal state from the stack
if (animalStates.length > 0) {
  let animals = JSON.parse(animalStates.pop());
  this.replaceState({...state, animals});
}

By following this approach, you can seamlessly merge different aspects of the state based on your requirements.

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

Incorporating stick-to-top scroll functionality using AngularJS and ng

I am trying to implement a 'sticky' scroll on dynamic content. My current working example can be found here. It seems to be working, but I encounter a small 'flicker' when new items are appended. This issue seems to be related to the se ...

Collapse or expand nested rows within a dynamic table using Bootstrap Collapse feature

I am currently working on creating a dynamic leaderboard table for a sports league using data from a SQL database. The league consists of multiple teams, each team has different players (with some players belonging to more than one team), and players earn ...

Ways to access the req.user object within services

After implementing an authentication middleware in NestJs as shown below: @Injectable() export class AuthenticationMiddleware implements NestMiddleware { constructor() {} async use(req: any, res: any, next: () => void) { const a ...

In search of a fresh and modern Facebook node template

I've been on the hunt across the internet for a quality node.js Facebook template, but all I seem to stumble upon is this https://github.com/heroku/facebook-template-nodejs. It's okay, but it's built using express 2.4.6 and node 0.6.x. I wan ...

What is the fewest amount of commands needed to generate a client-side Javascript code that is ready for use?

In the realm of JavaScript libraries found on Github, it has become increasingly challenging to integrate them directly into client-side projects with a simple script tag: <script src="thelibrary.js"></script> The issue arises from the browse ...

Creating a file by piping the output of an asynchronous HTTP request while utilizing async await method

I have been diligently following the instructions and conducting thorough research for a whole day to figure out how to use a pipe to compile an Excel spreadsheet that is fetched through an API call. I managed to get part of the way in saving it, but unfor ...

Combining strings in a JavaScript object

Can someone help me with concatenating strings within an object in JavaScript? I am parsing through an XML file to create a list of links in HTML. Each time I iterate through the loop, I want to add a new <li> element containing the link. How can I ...

Learn how to showcase the URL path of an image stored in MongoDB on the front end of a website with the help of Node

I've managed to save the image paths of the uploaded pictures. They are stored like this http://localhost/public/Images/okro.jpg. However, I'm unsure how to retrieve them from the database and showcase them on the frontend. Is there a method to ...

The data-tooltip feature displays information as [Object object]

There seems to be an issue with displaying text in the data-tooltip. Instead of showing the intended message, it is displaying [Object object]. import React from "react"; import { FormattedMessage } from "react-intl"; const translate = (id, value={}) = ...

Generate a new array of objects by cloning an existing array of objects with placeholder values

I am looking to transform an array of objects into another array of objects in order to generate a graph. Below is the array I am using to determine the position of each object within the new object. let uniqueSkills = ['Using', 'Analyzing ...

Tips for showcasing a calculated value in vue-table-2

When using an API to retrieve a dataset from a server, the date/time is in epoch format (eventTime). How can I convert this into a human-readable date/time format? What is the correct method for achieving this? Template for displaying table <div class ...

Adapt the class based on different string inputs

I am facing a challenge where I need to dynamically change the div class based on a variable value. The issue is that the variable can have multiple values that should all be considered as true in my case. isActive: "yes" These values can include: "true" ...

Issue with the demo code for Vue Stripe Checkout

As I delve into the world of Vue-Stripe-Checkout, I encountered a snag right from the start with the demo code provided. The issue arises when utilizing the Vue Stripe Elements component. Has anyone else experienced this problem? There are no errors displa ...

Dynamic properties in JQuery

Here is the HTML DOM element I have... <input type="text" style="width: 200px;" id="input1"/> I want to make sure it stores date values. How can I specify that in the DOM element? Please provide your suggestions. Thanks! ...

Executing function statement

I'm currently learning about React hooks, and I have a question regarding the behavior of two function expressions within different useEffect hooks. In one case, the function expression named timerId in the first useEffect is invoked automatically wit ...

Despite correctly declaring jquery-ui.js and numeric.js, the jQuery datepicker and numeric plugins are not working as expected

element, it's strange that I am not receiving any error messages. However, despite this, the jquery datepicker function and numeric plugin are not working on the intended input fields they are supposed to be linked to. This particular page is a simpl ...

What is the best way to detect when a user manually changes a dropdown selection?

Is there a way to detect when a user changes a dropdown option manually, rather than when the page loads and the default value is set? I attempted using e.originalEvent, but it didn't work as expected. $(self.options.selectChange).change(function (e ...

Challenges with the Sumo Select Refresh Feature

I am having trouble with Sumo select not refreshing the data properly. The action method is returning the correct list, but it seems like the JQUERY multi-select rebuild() function is missing. Is there something I'm overlooking? $("#ddlCountry&q ...

:after pseudo class not functioning properly when included in stylesheet and imported into React

I am currently utilizing style-loader and css-loader for importing stylesheets in a react project: require('../css/gallery/style.css'); Everything in the stylesheet is working smoothly, except for one specific rule: .grid::after { content: ...

Pause file uploads, display modal popup, then resume uploading

Is there a way to pause file uploading in order to display file requirements before proceeding? For example, when a user clicks on "upload file", I would like to show them a modal window with details about the file they need to upload. Once they click ok, ...