Special Character
Special Character

Reputation: 2359

types.reference not resolving the reference in mobx-state-tree

I am writing a search function that returns an array of ModelA or ModelB but when I use the references in my component, the reference is still a string. From the docs, I was expecting this to be the actual ModelA or ModelB so I feel like I am doing something wrong.

In my root store I create an array of references like this:

searchResults: types.array(
      types.union(
        types.late(() => types.reference(ModelA)),
        types.late(() => types.reference(ModelB)),
      ),
),

When I get them back from the request they are loaded into the store (I check by doing store.modelBs.get(<one of the ids>) but the component still gets the array of strings:

enter image description here

Does anyone know if this is valid/what I am doing wrong here?

Upvotes: 3

Views: 2351

Answers (1)

Special Character
Special Character

Reputation: 2359

For posterity, I found that it isn't possible to have an array of references that contain more than one type. Mobx-state-tree cannot determine what type of model the id references and throws the error: Failed to resolve reference 'idB1' to type 'AnonymousModel'.

CodeSandbox example

edit: The way to accomplish this is to use the dispatcher config option for the union type like in this comment: https://github.com/mobxjs/mobx-state-tree/issues/1162#issuecomment-459742443

Upvotes: 3

Related Questions