Skip to content

Instantly share code, notes, and snippets.

@Soreine
Last active May 7, 2020 10:13
Show Gist options
  • Save Soreine/3af64e8f99ce1ff6b4e2e452c75c0c23 to your computer and use it in GitHub Desktop.
Save Soreine/3af64e8f99ce1ff6b4e2e452c75c0c23 to your computer and use it in GitHub Desktop.
Undo using Command pattern. The Command objects can be anonymous functions
// This is some pseudocode
function onArchiveAndNext(threadId) {
dispatch(archiveThread(threadId));
dispatch(sortingGoToNext(thread));
// We can define the undo logic right next to the effect to undo.
// This also means any part of the UI can define its own undoable effect.
const undoCommand = () => {
dispatch(moveToInbox(threadId));
dispatch(sortingGoToPrevious(thread));
}
dispatch(pushUndo(undoCommand));
}
function onUndo() {
dispatch(undo());
}
... UI code
function undo() {
return async (getState, dispatch) => {
const lastUndoCommand = getState().undos.pop();
// The undo actions/reducers have no clue about the inner working of what is being undone
// Better encapsulation
await lastUndoCommand();
// on success, clear that last command
dispatch(clearLastUndo());
}
}
function pushUndo(undoCommand: () => void | Promise<void>) {
// add undoCommand to the queue
}
function clearLastUndo() {
// pop last undoCommand from the queue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment