Redux State Shape for One-to-Many Relationships
Asked Answered
S

1

9

When designing a state shape with related entities, the official Redux docs recommend referencing by ID rather than nesting: http://redux.js.org/docs/basics/Reducers.html#note-on-relationships.

In a one-to-many relationship, Normalizr will put the references in the "one" side of the relationship, e.g.:

"posts": {
  "1": {
    ...
    comments: ["1", "2", "3"]
...

Is this better than putting the reference in the "many" side? e.g.

"comments": {
  "7": {
    ...
    postId: "1"
...

Does it matter where I put the reference when creating a Redux store?

Sacral answered 5/10, 2017 at 4:44 Comment(0)
C
3

I'd suggest keeping the ID of the comments in the post.

This way, for any given post, you can access all the comments by direct reference (index or property name, it doesn't matter), which is fast and easy. That's a complexity of O(N).

In the opposite scenario, you'll have to search your whole comments for any given post. That's a complexity of O(N^2). Plus, you'll have to re-order your comments once you have them all.

Chenopod answered 12/5, 2018 at 17:14 Comment(1)
The added benefit to keeping comment IDs on the post, instead of the other way around, is that it gives you a way to order comments.Conard

© 2022 - 2024 — McMap. All rights reserved.