Last active
May 7, 2020 10:13
-
-
Save Soreine/3af64e8f99ce1ff6b4e2e452c75c0c23 to your computer and use it in GitHub Desktop.
Undo using Command pattern. The Command objects can be anonymous functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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