3

Let say i have this state:

{
  "appointments": {
    "ids": [...],
    "entities": [
        "0": {
            ...
            mandatoryRecipients: ['0','3']
        },
        "1": {
            ...
            mandatoryRecipients: ['1','2','0']
        }
    ]
  },
  "recipients": {
    "ids": [...],
    "entities": [
        "0": {
            ...
            id: '0',
            name: 'foo'
        },
        "1": {
            ...
            id: '1',
            name: 'foobar'
        },
        "2": {
            ...
            id: '2',
            name: 'bar'
        }
    ]
  }
}

At a certain point, I need to add a value into the 'mandatoryRecipients' array of the appointment entity. I know that this state is not normalized but how can I normalize it in order to accomplish a many to many relationship?

  • 1
    You probably don’t want to have a situation where you let 2 or more entities depend on each other (i.e. if you update one you HAVE to update another one). The connection between entities is best made in the selector that gets the data if that makes sense.. – MikeOne May 21 '20 at 12:05

2 Answers2

1

You need to use a lib for that. Manually it will take too much effort to cover everything.

You can use ngrx-entity-relationship.

Like that for example.

const fullAppointment = rootEntity(
  selectAppointments, // feature selector, EntityState<Appointment>
  relatedEntity(
    selectRecipients, // related feature selector, EntityState<Recipient>
    'mandatoryRecipients', // key with ids
    'mandatoryRecipientsEntities', // key to assign related entities
  ),
);

const fullAppointments = rootEntities(fullAppointment);

store.select(fullAppointments, ['0', '1']).subscribe(value => {
  // value[0].mandatoryRecipientsEntities[0].name works!
});

or if you use createSelector then

const selectFullAppointments = createSelector(
  selectIds,
  v => v,
  (ids, store) => fullAppointments(store, ids);
);
satanTime
  • 12,631
  • 1
  • 25
  • 73
0
 interface Appointment {
  id: string;
}

 interface MandatoryRecepient {
   id: string;
   recepientId: string;
   appointmentId: string;
 }

 interface Recepient {
  id: string;
  name: string;
}
Alex Nazarevych
  • 456
  • 4
  • 7