Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an array of all `ids` needed in a normalized state shape?

Tags:

normalizr

comments : {
    byId : {
        "comment1" : {
            id : "comment1",
            author : "user2",
            comment : ".....",
        },
        "comment2" : {
            id : "comment2",
            author : "user3",
            comment : ".....",
        },
        "comment3" : {
            id : "comment3",
            author : "user3",
            comment : ".....",
        },
        "comment4" : {
            id : "comment4",
            author : "user1",
            comment : ".....",
        },
        "comment5" : {
            id : "comment5",
            author : "user3",
            comment : ".....",
        },
    },
    allIds : ["comment1", "comment2", "comment3", "commment4", "comment5"]
}

In the above example, is there any reason my needs to include it api include it. I assume this way you can do a count faster, you can probably sort but generally I am not understanding if there is a performance hit.

like image 603
nolawi Avatar asked Sep 08 '17 21:09

nolawi


People also ask

Why is it recommended to normalize the state?

A normalized state is a way to store (organize) data. With this way each entity type will have its own place in the store, so that there is only a single point of truth. This practice is the recommended way to organize data in a Redux application as you can read in the Redux recipes.

What is normalized data Redux?

Redux and Normalization Normalization is the concept of flattening data and this comes with great performance increases because data is referenced directly and instantly rather than looped over. This is because normalized nested data is represented by ids which are later used to reference that data.

How normalize data react?

To normalize the data, store the unique identifiers of each object in a separate array. Let's call that array as results . And transform the array of objects into an object with keys as the id (See the second snippet). Call that object as entities .


1 Answers

This isn't anything that's required by Redux, this is a normalizr thing. To answer your question, JavaScript objects can't be replied upon to retain sort order in certain situations. Putting the ids in an array allows you to retain the sort order that was present before you normalized.

Quote from co-maintainer of Redux and author of "normalizing state shape section" of Redux docs:

As for the ID arrays, while JS engines now have a fairly standardized process for iterating across keys in an object, you shouldn't rely on that to define ordering. Storing arrays of IDs allows you to define an order for items.

like image 181
Rob Wise Avatar answered Nov 14 '22 04:11

Rob Wise