Get a model properties initial value #1714
-
Is there a way to get a model's initial value for a given property? Basically, I'm trying to determine if something has been changed from its original value to display it or not. I suppose I could have a property on the model that denotes if it's "dirty" and gets changed whenever that model gets updated? Didn't know if there was an easier way to just get the initial value for a given property to compare it to the current value of the same property or not |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
AFAIK, there isn't. When I needed this functionality, I assigned the initial data to an identifier in the module file of the model, used that as the initial value and could compare subsequent snapshot values to it in MST views and actions. |
Beta Was this translation helpful? Give feedback.
-
There is no way to check the initial values of a model instance out of the box, but you could e.g. store the initial values in a volatile state variable in the Example (CodeSandbox) import { observer } from "mobx-react-lite";
import { getSnapshot, types } from "mobx-state-tree";
const MyModel = types
.model({
foo: "bar",
num: 42
})
.volatile(() => ({
initialValues: undefined
}))
.views((self) => ({
get renderedNum() {
return self.num !== self.initialValues.num ? self.num : undefined;
}
}))
.actions((self) => ({
afterCreate() {
self.initialValues = getSnapshot(self);
},
setNum(num) {
self.num = num;
}
}));
const myModel = MyModel.create();
setTimeout(() => myModel.setNum(1337), 1000);
setTimeout(() => myModel.setNum(42), 3000);
export default observer(function App() {
return (
<div>
<h1>{myModel.renderedNum}</h1>
</div>
);
}); |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
export const getInitialSnapshot = self => self.$treenode._initialSnapshot