Does detach remove the computed values from cache? #2133
-
Looking at source code mobx-state-tree/src/core/node/object-node.ts Lines 499 to 503 in e93d97d it eventually calls If not, is there some other way to somehow copy a node along with its computed values? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
@Dummy26 - I think so. Here's an experiment that seems to evaluate a computed view after the model was detached: https://codesandbox.io/p/sandbox/silly-galileo-ly4msx?file=%2Fsrc%2Findex.ts%3A17%2C22 Code: import { t, detach } from "mobx-state-tree";
const Car = t
.model({
brand: t.string,
model: t.string,
year: t.number,
})
.views((self) => ({
get makeModelYear(): string {
const { brand, model, year } = self;
console.log("evaluating");
return `${brand} ${model} ${year}`;
},
}));
const ParentModel = t
.model({
car: t.maybe(Car),
})
.actions((self) => ({
detachCar() {
detach(self.car);
},
}));
const myCar = Car.create({
brand: "Subaru",
model: "Outback",
year: 2019,
});
const parent = ParentModel.create({
car: myCar,
});
// Double check the cache is working as expected.
console.log("one", myCar.makeModelYear); // Expect to see "Evaluating" once before this
console.log("two", myCar.makeModelYear); // Cached, should not see it here
parent.detachCar();
// After detaching,
console.log("after detach", myCar.makeModelYear); // "evaluating" prints again |
Beta Was this translation helpful? Give feedback.
-
To your second question about moving the computed values over, I don't know of a built-in way to do it, but you could write another view on your object that basically takes a snapshot of itself and then enriches it with computed values at the time you evaluate it. Like:
https://codesandbox.io/p/sandbox/clever-mclaren-895qdg?file=%2Fsrc%2Findex.ts%3A34%2C1 There might be something you can do with snapshot processing hooks as well. |
Beta Was this translation helpful? Give feedback.
@Dummy26 - I think so. Here's an experiment that seems to evaluate a computed view after the model was detached:
https://codesandbox.io/p/sandbox/silly-galileo-ly4msx?file=%2Fsrc%2Findex.ts%3A17%2C22
Code: