References (safe or not) and onInvalidated
#2188
-
Hey guys, From the get started sandox, I've added a check whenever the reference to User from Todo is invalid: https://codesandbox.io/s/mobx-state-tree-getting-started-13-forked-m7352x?file=/index.js user: types.maybe(
types.reference(
types.late(() => User),
{
onInvalidated: (e) => console.warn(e)
}
)
) Why does With a Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Hi @cavasinf - looks like that CodeSandbox is private. Would you mind making it public so I can take a look? Thanks! |
Beta Was this translation helpful? Give feedback.
-
Hi @cavasinf - this is a subtle issue. Very reasonable to get tripped up by it (it took me a few minutes to debug it haha). In your So when it's instantiated, MobX-State-Tree says "hmm, I don't know about a user with the ID of 3, this is invalid". This is not the case in your original Here is a code sandbox that no longer warns the invalidation: https://codesandbox.io/p/sandbox/mobx-state-tree-getting-started-13-forked-23jcls?file=%2Findex.js%3A90%2C16 Here's the diff: In the updated code, I create the Once the Notice in your original example: changing users works totally fine, as well. Again, that's because the Does that answer your question? Happy to dig in more if I've missed some other part of the example code. References are a useful tool but they can be tricky. |
Beta Was this translation helpful? Give feedback.
Hi @cavasinf - this is a subtle issue. Very reasonable to get tripped up by it (it took me a few minutes to debug it haha).
In your
addTodo
action, you're setting the reference to theUser
instance in a newly createdTodo
. But thatTodo
is not yet part of the tree with the reference available.So when it's instantiated, MobX-State-Tree says "hmm, I don't know about a user with the ID of 3, this is invalid".
This is not the case in your original
store
creation call, sincetodos
exists in the same tree asusers
whenTodo
of ID1
is instantiated.Here is a code sandbox that no longer warns the invalidation: https://codesandbox.io/p/sandbox/mobx-state-tree-getting-started-13-forked-23jcls?fil…