Skip to content

Instantly share code, notes, and snippets.

@iskenxan
Created May 23, 2021 18:01
Show Gist options
  • Save iskenxan/cad36ee343569f728ad56f9fa9d81626 to your computer and use it in GitHub Desktop.
Save iskenxan/cad36ee343569f728ad56f9fa9d81626 to your computer and use it in GitHub Desktop.
import produce, { applyPatches, enablePatches } from "immer";
enablePatches();
export const RESET = "RESET";
export const OPEN_DOOR = "OPEN_DOOR";
export const UNDO = "UNDO";
let inverseChanges = [];
export const reducer = (state, action) => {
return produce(
state,
(draft) => {
switch (action.type) {
case OPEN_DOOR: {
const { index } = action.payload;
draft.doors[index].isOpen = true;
break;
}
case RESET: {
draft.doors = generateDoors();
inverseChanges = [];
break;
}
case UNDO: {
if (inverseChanges.length > 0) {
return applyPatches(state, [inverseChanges.pop()]);
}
break;
}
default:
break;
}
},
(patches, inversePatches) => {
if (action.type === OPEN_DOOR) {
inverseChanges.push(...inversePatches);
}
}
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment