Normalized Data in State - Tuong-Nguyen/JavaScript-Structure GitHub Wiki
Basic concepts
- Each type of data is a "table" in the
state
- Each "table" should store individual items in an object, with IDs as keys and items as the values
- Any reference to an item is it's ID
- Arrays of IDs is used to indicate ordering
{
posts : {
byId : {
"post1" : {
id : "post1",
author : "user1",
body : "......",
comments : ["comment2"]
},
"post2" : {
id : "post2",
author : "user2",
body : "......",
comments : ["comment1"]
}
}
allIds : ["post1", "post2"]
},
comments : {
byId : {
"comment1" : {
id : "comment1",
author : "user2",
comment : ".....",
},
"comment2" : {
id : "comment2",
author : "user3",
comment : ".....",
}
},
allIds : ["comment1", "comment2"]
},
users : {
byId : {
"user1" : {
username : "user1",
name : "User 1",
}
"user2" : {
username : "user2",
name : "User 2",
}
},
allIds : ["user1", "user2"]
}
}
Achievements
- Update item in only one place by making a new copy of the item
- The
reducer
logic does not have to deal with deep levels of nesting
- Logic for retrieving or updating a item is simple and consistent
Normalizing Nested Data
- Data needs to be transformed into a normalized shape before it can be included in the state tree
- We can define schema types and relations and use normalizr to get normalized transformation of the response from schema and response data