简体   繁体   中英

Preventing invalid state when dealing with related entities

Consider a (ReactJS) application where a Group and User entity are related to each other by a many-to-many relationship.

The state tree looks like this:

{
  groups: {
    "1": {id: "1", name: "..."}, 
    ...
  },
  users: {
    "42": {id: "42", name: "..."}, 
  ...
  },
  memberships: [
    {groupId: "1", userId: "42"}, 
    ...
  ]
}

In the UI, the user can "select" zero or more groups with zero or more associated users per group. This is currently represented in state like this:

{
  selectedGroupIds: {
    "1": {selectedUserIds: ["42", ...]}, 
    ...
  }
}

(as an aside, the following design might be preferable the one above since it's more explicit; would appreciate comments on that):

 { selectedGroupIds: [ {id: "1", selectedUserIds: ["42", ...]}, ... ] } 

Anyway, back to the main question:

Currently, when a user is selected within the context of a group, and at some point the group and user get disconnected (membership ends, user gets deleted, etc.), then selectedGroupIds will be in an invalid state. While writing this, I now realize this also applies to memberships when either groups or users are deleted.

Is there any way to design the state tree such that the above scenario will be prevented from happening? Or is manual housekeeping unavoidable in case of changing relationships?

When membership ends, user gets deleted, etc. you have to update the state and remove broken relations in cascade-style. This is not any different than other state update based on relation.

You can also make your arrays conditional if you do not want to update relations in your data:

memberships: [
    groups["1"] && users["42"] && {groupId: "1", userId: "42"}, 
    ...
  ].filter(o => o); // the filter is to ensure to remove null values that could be generated by conditions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM