Correct way to store editable model #1679
-
Hey guys, For example, this is my state tree:
as you see I using I tried to use |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey @R-iskey! One way of going about it is to use a Example import { observer } from "mobx-react-lite";
import {
applySnapshot,
getSnapshot,
Instance,
SnapshotIn,
types
} from "mobx-state-tree";
const ActivityModel = types
.model("ActivityModel", {
id: types.identifier,
room: types.string,
namespace: types.string
})
.actions((self) => ({
setRoom(room: string) {
self.room = room;
}
}));
type ActivityModelInstance = Instance<typeof ActivityModel>;
type ActivityModelSnapshotIn = SnapshotIn<typeof ActivityModel>;
const ActivitiesModel = types
.model("ActivitiesModel", {
data: types.array(ActivityModel),
beingEdited: types.maybeNull(types.reference(ActivityModel))
})
.actions((self) => {
let activitySnapshot: ActivityModelSnapshotIn;
return {
edit(activity: ActivityModelInstance) {
activitySnapshot = getSnapshot(activity);
self.beingEdited = activity;
},
submit() {
self.beingEdited = null;
},
cancel() {
applySnapshot<ActivityModelSnapshotIn>(
self.beingEdited!,
activitySnapshot
);
self.beingEdited = null;
}
};
});
const activities = ActivitiesModel.create({
data: [
{
id: "1",
room: "room 1",
namespace: "namespace 1"
},
{
id: "2",
room: "room 2",
namespace: "namespace 2"
}
]
});
export default observer(function App() {
const { data, beingEdited } = activities;
return (
<div>
{data.map((activity) => (
<div key={activity.id}>
{beingEdited === activity ? (
<>
<input
value={activity.room}
onChange={(e) => activity.setRoom(e.target.value)}
/>
<button onClick={activities.submit}>Save</button>
<button onClick={activities.cancel}>Cancel</button>
</>
) : (
<>
<span>{activity.room}</span>
{beingEdited === null && (
<button onClick={() => activities.edit(activity)}>Edit</button>
)}
</>
)}
</div>
))}
</div>
);
}); |
Beta Was this translation helpful? Give feedback.
Hey @R-iskey!
One way of going about it is to use a
reference
to the model you are editing instead of cloning it. You can then store a snapshot of the model just as you start to edit it, and revert the model back to this snapshot if you cancel the edit.Example