Using UndoManager as a volatile state #1870
-
I'm trying to implement undo\redo support in an open source project I'm attempting to contribute to. As a beginner I'm struggling and would love some assistance. if the What I've tried: as per this thread: #1232 Another option is to record the changes into a different tree, as stated in the docs, but I could not figure out how to do that and how it would work. I'd love some assistance as I have no idea how to proceed. Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @Guy-Rahamim! Like you noticed the Example import { observer } from "mobx-react-lite";
import { types } from "mobx-state-tree";
import { UndoManager } from "mst-middlewares";
const Person = types
.model({
name: types.string,
age: types.number
})
.volatile((self) => ({
undoManager: UndoManager.create({}, { targetStore: self })
}))
.views((self) => ({
get canUndo() {
return self.undoManager.canUndo;
},
get canRedo() {
return self.undoManager.canRedo;
}
}))
.actions((self) => {
return {
setName(name) {
self.name = name;
},
setAge(age) {
self.age = age;
},
undo() {
self.undoManager.undo();
},
redo() {
self.undoManager.redo();
}
};
});
const person = Person.create({ name: "John Doe", age: 30 });
export default observer(function App() {
return (
<div>
<button onClick={person.undo} disabled={!person.canUndo}>
{"<"}
</button>
<input
value={person.name}
onChange={(e) => person.setName(e.target.value)}
/>
<input
value={person.age}
type="number"
step="1"
min="0"
onChange={(e) => person.setAge(Number(e.target.value))}
/>
<button onClick={person.redo} disabled={!person.canRedo}>
{">"}
</button>
</div>
);
}); |
Beta Was this translation helpful? Give feedback.
Hi @Guy-Rahamim!
Like you noticed the
history
returned from the volatile block is not an initialized model, you have to create it yourself.Example