user1813867
user1813867

Reputation: 1055

Modeling the state-tree in React Redux

I'm trying to learn redux and one of the things not clear to me is how to model the data in the state tree. Take a simple evernote type application where there are many notebooks and each notebook has many notes. One possible representation of the state tree would be something like this:

{
  notebooks:[
    {
      id: 0
      notes:[
        "hey",
        "ho",
        "let's go"
      ]
    },
    {
      id: 1
      notes:[
        "another",
        "notebook"
      ]
    }
  ]
}

But then I've also read it's not good to have a deeply nested state tree and instead state should be stored in a more normalized way, almost as though it were a structured database. So in that case, would it be better to model the data like this?

{
  notebooks: [
    {
      id: 0
    },
    {
      id: 1
    }
  ]
  notes: [
    {
      notebook_id: 0,
      note: "hey"
    }
    {
      notebook_id: 0,
      note: "ho"
    },
    {
      notebook_id: 0,
      note: "let's go"
    },
    {
      notebook_id: 1,
      note: "another"
    },
    {
      notebook_id: 1,
      note: "notebook"
    }
  ]
}

Or is there a 3rd and even better way?

Upvotes: 0

Views: 335

Answers (2)

markerikson
markerikson

Reputation: 67459

Close. For nested/relational data, you want to think of your Redux state as if it were a database with "tables". It's generally easiest if you keep all the "real" objects in a lookup table keyed by ID, and then all other references simply use the appropriate ID:

{
    notebooks : {
        byId : {
            0 : { notes : [0, 4]},
            1 : { notes : [1, 2, 3]}
        },
        ordered : [0, 1]
    },
    notes : {
        byId : {
            0 : {notebook : 0, note : "hey"},
            1 : {notebook : 1, note : "ho"},
            2 : {notebook : 1, note : "let's go"},
            3 : {notebook : 1, note : "another"},
            4 : {notebook : 0, note : "notebook"}
        }
    }
}

Per the other comment, the Normalizr library can help with this. I also really like a library called redux-orm, which helps maintain the relationships.

Finally, you might want to refer to the Redux FAQ answer on organizing nested state.

Upvotes: 0

Rafael Quintanilha
Rafael Quintanilha

Reputation: 1432

You got it right. If you opt for normalize your data, have a look at the Normalizr library.

Upvotes: 1

Related Questions