Skip to content

Instantly share code, notes, and snippets.

@elpete
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elpete/b6d5c32e1f92cb949819 to your computer and use it in GitHub Desktop.
Save elpete/b6d5c32e1f92cb949819 to your computer and use it in GitHub Desktop.
Undo Redo Mixin for React
var UndoRedoMixin = {
componentWillMount: function() {
this.undoAction = false;
this.redoAction = false;
this.pastStates = [];
this.futureStates = [];
},
componentDidUpdate: function(prevProps, prevState) {
if (this.undoAction) {
this.futureStates.push(prevState);
this.undoAction = false;
return;
}
this.pastStates.push(prevState);
if (!this.redoAction) {
this.futureStates = [];
}
this.redoAction = false;
},
undo: function() {
var undoState = this.pastStates.pop();
if (!this.pastStates.length) {
this.pastStates.push(undoState);
}
if (this.state !== undoState) {
this.undoAction = true;
this.setState(undoState);
}
},
redo: function() {
var redoState = this.futureStates.pop();
if (redoState) {
this.redoAction = true;
this.setState(redoState);
}
}
};
module.exports = UndoRedoMixin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment