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)
.