Senior LevelVue JS
How do you implement time-travel debugging and Undo/Redo state snapshots in Pinia?
❓ Interview Prompt: Explain state snapshot history stacks, store.$subscribe(), and implementing Undo/Redo functionality in Pinia.
Complex web applications (like graph editors or form builders) require Undo/Redo state history management.
Implementing Pinia Undo/Redo:
1
Subscribe to store state mutations using 'store.$subscribe((mutation, state) => ...)'.
2
Push deep-cloned state snapshots into a 'historyStack'.
3
To Undo: Pop the previous state snapshot from 'historyStack' and restore state using 'store.$patch(previousState)'!
Code Implementation Example
javascript
export function createUndoRedoPlugin(store) {
const history = [];
let currentIndex = -1;
store.$subscribe((mutation, state) => {
// Record state snapshot
history.push(JSON.parse(JSON.stringify(state)));
currentIndex = history.length - 1;
});
return {
undo() {
if (currentIndex > 0) {
currentIndex--;
store.$patch(history[currentIndex]); // Restore state snapshot!
}
}
};
}💡Building a time-travel Undo/Redo plugin for Pinia using store.$subscribe and $patch.
🎯 Interview Key Takeaway
Use store.$subscribe to capture state snapshots into a history stack and store.$patch() to restore previous state for Undo/Redo.
#Pinia#Undo Redo#State History#Senior
Back to all Vue JS Questions→