mobxjs / mst-gql

Bindings for mobx-state-tree and GraphQL
MIT License
681 stars 81 forks source link

Locally instantiated model causing "Failed to resolve reference" error #411

Open KashubaK opened 1 year ago

KashubaK commented 1 year ago

I have two models: CheckoutModel and ItemModel. I want to be able to create a local CheckoutModel to add ItemModels to before saving. However on my first try, after adding an item to my checkout.items and executing a view on the checkout to calculate the total cost, this error was produced:

Failed to resolve reference 63d6f382a0afdb03a9a1b53d to late(() => ItemModel)

It appears that locally created models are detached from the RootStore which is causing the error (which makes total sense.) The workaround is to manually set the store on the new instance:

import { rootStore } from 'wherever/your/rootStore/is';

const Cart = observer(() => {
  const checkout = useLocalObservable(() => CheckoutModel.create({ id: 'X' }));

  checkout.__setStore(rootStore);

  // blah blah blah
});

This is weird, and makes me feel like I shouldn't be doing this at all. I suppose I should just be creating a new model to only be used for local state, but I don't want to wind up having to do this for every applicable model in my application. For now I'll be abstracting this behind some useLocalInstance hook, or within an afterCreate in my models.

Any thoughts are definitely appreciated!