-
Hello. Could you please tell what is going on here? import { getSnapshot, types } from 'mobx-state-tree'
const fooModel = types.model({
id: types.identifier,
title: types.string,
})
const barModel = types.model({
id: types.identifier,
foo: types.reference(fooModel),
})
const foo = fooModel.create({
id: 'foo',
title: 'foo',
})
const bar = barModel.create({
id: 'bar',
foo: foo,
})
console.log(getSnapshot(bar)) // => { id: 'bar', foo: 'foo' }
console.log(bar.foo)
// InvalidReferenceError: [mobx-state-tree] Failed to resolve
// reference 'foo' to type 'AnonymousModel' (from node: /foo) It's almost the same as the example from the docs: import { types } from 'mobx-state-tree'
const Todo = types.model({
id: types.identifier,
title: types.string,
})
const TodoStore = types.model({
todos: types.array(Todo),
selectedTodo: types.reference(Todo),
})
// create a store with a normalized snapshot
const storeInstance = TodoStore.create({
todos: [
{
id: '47',
title: 'Get coffee',
},
],
selectedTodo: '47',
})
// because `selectedTodo` is declared to be a reference, it returns the actual Todo node with the matching identifier
console.log(storeInstance.selectedTodo.title)
// prints "Get coffee" I don't have "stores", I have a number of connected models. So how do I connect them then? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
With a store, or something like that 🙂 But it helps to explain why! References are resolved within the tree they're part of, but they can't resolve identifiers across different trees. For you, For example, for you, it could look like this: import { getSnapshot, types } from 'mobx-state-tree'
const fooModel = types.model({
id: types.identifier,
title: types.string,
})
const barModel = types.model({
id: types.identifier,
foo: types.reference(fooModel),
})
const foobarStore = types.model({
foo: fooModel,
bar: barModel,
});
const store = foobarStore.create({
foo: { id: 'fooId', title: 'foo' },
bar { id: 'barId', foo: 'fooId' },
});
console.log(store.bar.foo) |
Beta Was this translation helpful? Give feedback.
With a store, or something like that 🙂
But it helps to explain why! References are resolved within the tree they're part of, but they can't resolve identifiers across different trees. For you,
foo
andbar
are two separate trees (specifically, they're the roots of two trees). In the docs example, everything is under one tree rooted atstoreInstance
, so that's why the references can resolve.For example, for you, it could look like this: