Search code examples
reactjsnormalizr

How can I use the result array in my normalized state to render posts in sorted order


I have successfully used normalizr in my react app to normalize my API response. In my state, I have entities and the result array. I am using the entities to render posts in my react component but they are not in their original order.

I understand that the entities is an object, therefore it will not maintain the order. I also understand that i must use the result array since it has the ids in the original order. My questions is how do I go about using this result array in my react component to display the posts in their original order?

I have searched through the stack + google and I seem not to find a specific answer that addresses my question. I have also tried to do a sort before I map the entities object in my render as follows:

Object.values(posts).sort((a, b) => a.created_on > b.created_on)

or

Object.values(posts).sort((a, b) => a.created_on + b.created_on)

or

Object.values(posts).sort((a, b) => a.created_on - b.created_on)

and then using map. But all these do not work.

Is there a specific way to do this without using denormalizr?

Thanks in advance.


Solution

  • Thanks a lot. However...

    I just figured out that the sort method is not necessary in my render since I am using normalizr which already has a result array of all posts in the correct order by their IDs while obviously all posts data is in the entities object.

    So I managed to map through that normalizr result array which holds all the key ids of every post and then return a new object with every post in the entities object sorted by its respective key id.

    As this...

    resultArray.map(post => postEntities[post]);
    

    This gets all the posts in their correct order since I am mapping through the already ordered result array.

    By the way, I am using selectors for this. So the code above is not in the render component but is in the selectors.js