Entity sorting after updates is not stable
See original GitHub issuePer https://www.reddit.com/r/reduxjs/comments/ud58hg/sortcomparer_in_rtk_switches_the_ordering_of/ :
I’m using createEntityAdapter with sortComparer to sort some entities based on a timestamp for when they were last updated. If the entities haven’t been updated yet, this timestamp is null. There are many cases of these null timestamps in my data.
I’m displaying these sorted entities in a table, where I can also make edits that will modify the entity object by dispatching an action, which uses the updateOne entity adapter method. Note that this edit has no impact on the timestamp used for sorting.
My problem is: if I edit an entity which has a matching timestamp as other entities (this happens often in the case of null timestamps), that item will suddenly be re-ordered to appear at the bottom of my table.
It seems like this happens because the sortComparer function returns 0 since the comparison is equal, so the order is then based on the ordering of entities in my slice. But because the entity was updated, redux re-orders the entity in the slice to now be at the bottom (which I can see happening using the redux dev tools). This means that any time I change an entity that has an equal sort comparison, it will now be automatically reordered to be last.
Is there any way around this? It seems crazy to me that I can’t rely on a consistent ordering for items that have an equal comparison.
My analysis:
Hmm. We ultimately just call
array.sort()
with whatever sorting comparator you provided.However, given that it’s doing
Object.values(entities)
, the order of items in that array is going to be based on insertion order into that object, I think. Given that the update logic is implemented by deleting the existing item ID fromstate.entities
before it gets re-added later, I can see how that might result in an updated item technically getting added later.
Issue Analytics
- State:
- Created a year ago
- Comments:5
This should actually be fixed now in #2464 and will be out in whatever the next patch or minor release is.
@markerikson : i’m using version 1.8.1. Maybe i need to upgrade. Thanks for the info.