Limbo
Limbo

Reputation: 2290

MobX State Tree: get a list of references that are using specific identifier

Well, the question is quite straight-forward. Assume we have some model with identifier

const ReferableModel = types.model({
  id: types.identifier(),
})

and an indefinite number of models that can refer to this model

const Model1 = types.model({
  ref: types.maybe(types.reference(ReferableModel)),
})
const Model2 = types.model({
  ref: types.maybe(types.reference(ReferableModel)),
})
// and so on

These models can be at any place of the tree.

So, the question is: Is it possible to list (or, at least, count) models that refer to specific identifier WITHOUT ADDITIONAL FRICTION? I mean, yeah, we can always count such things manually, but I wonder if I'm missing docs or something (e.g. types.refinement) and there is some out-of-box method.

Thanks in advance

Upvotes: 0

Views: 110

Answers (1)

Artur Minin
Artur Minin

Reputation: 1240

In MobX, there is no built-in method that automatically lists or counts models that refer to a specific identifier. However, you can create a utility function to achieve this. This utility function will traverse the tree and count references to a specific ReferableModel by its identifier:

function countReferences(tree, identifier) {
  let count = 0;

  function traverse(node) {
    if (node.ref && node.ref.id === identifier) {
      count++;
    }
    node.children?.forEach(traverse);
  }

  traverse(tree);

  return count;
}

Upvotes: 1

Related Questions