mobx-state-tree

MST: define model with children of itself


Just started to fiddle around with Mobx-state-tree.

I have this model, that has parent and children properties that can be filled with instances of the same model.

So basically something like this:

const Page = types.model({
    guid: types.string,
    title: types.string,
    description: types.string,
    parent: types.union(Page, types.undefined),
    children: types.array(Page),
})

But, obviously Page is not available yet on the creation of this model.

How can I do this?


Solution

  • After minutely reading the docs, I found the answer. Using types.late():

    const Page = types.model({
        guid: types.string,
        title: types.string,
        description: types.string,
        parent: types.union(types.late(() => Page), types.undefined),
        children: types.optional(types.array(types.late(() => Page)), []),
    })