0

I have a database containing a table of organisations with properties orgref, parentorgref, name.

{ orgref: 1, name: "Level 0 org" }
{ orgref: 2, parentorgref: 1, name: "Level 1 org A" }
{ orgref: 3, parentorgref: 1, name: "Level 1 org B" }
{ orgref: 4, parentorgref: 3, name: "Level 2 org" }

I store these organisations in an rxjs entity state.

In most places in my application, I want to use these hierarchically (data trees etc) so want them arranged as:

{
  orgref: 1,
  name: "Level 0 org",
  children: [{
    orgref: 2,
    parentorgref: 1,
    name: "Level 1 org A"
  }, {
    orgref: 3,
    parentorgref: 1,
    name: "Level 1 org B",
    children: [{
      orgref: 4,
      parentorgref: 3,
      name: "Level 2 org",
    }]
  }]
}

Of course, if I add the sub-organisations to the children collection when I load the organisations via

{
  ...org,
  children: getChildrenRecursive()
}

then the reference to the entity is broken - that is, if I edit the entity with orgref=3, it won't update the organisation within the hierarchy because it it a copy of the object, rather than a reference to it.

Is there an accepted solution for dealing with hierarchical entities in an ngrx EntityState?

Thanks

EricP
  • 173
  • 2
  • 14
  • 2
    It would be best if you keep your object flat with property `parentId` so that you can reference. Whenever you need the hierarchy data for your data tree you would just map/group them. – penleychan Dec 19 '19 at 17:32
  • Thanks. If you reply as a full answer I can mark this as correct. – EricP Jan 06 '20 at 18:45

2 Answers2

0

please take a look at ngrx-entity-relationship: https://www.npmjs.com/package/ngrx-entity-relationship.

It can help you to solve your issue.

Your selector would looks like:

const select entityWithChildren = rootEntity(
  selectYourEntityState, // <- replace with the selector of the entity state.
  childrenEntity(
    selectYourEntityState, // <- replace with the selector of the entity state.
    'parentorgref',
    'children',
  ),
);

and then in components / services:

store.select(entityWithChildren, 1);
satanTime
  • 12,631
  • 1
  • 25
  • 73
0

Best practice is to keep your state flat, with relational data normalized.

Selectors are in charge to query/select slide of state, and make some aggregation if necessary.

Update are easy, simple and there is only a source of truth.

See this question and answer about Redux pattern.

Thierry Falvo
  • 5,892
  • 2
  • 21
  • 39