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

1.7k views Asked by At
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.

1

There are 1 answers

3
Rob Wise On BEST ANSWER

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.