Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/toolkit/src/entities/sorted_state_adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,16 @@ export function createSortedStateAdapter<T, Id extends EntityId>(
newEntities: readonly T[] | Record<Id, T>,
state: R,
): void {
let deduplicatedEntities = {} as Record<Id, T>;
newEntities = ensureEntitiesArray(newEntities)
if (newEntities.length !== 0) {
for (const item of newEntities) {
delete (state.entities as Record<Id, T>)[selectId(item)]
const entityId = selectId(item);
// For multiple items with the same ID, we should keep the last one.
deduplicatedEntities[entityId] = item;
delete (state.entities as Record<Id, T>)[entityId]
}
newEntities = ensureEntitiesArray(deduplicatedEntities);
mergeFunction(state, newEntities)
}
}
Expand Down
19 changes: 19 additions & 0 deletions packages/toolkit/src/entities/tests/sorted_state_adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,25 @@ describe('Sorted State Adapter', () => {
expect(withOneSorted).toEqual(withOneUnsorted);
})

it('should work consistent with Unsorted State Adapter adding duplicate ids', () => {
const unsortedAdaptor = createEntityAdapter({
selectId: (book: BookModel) => book.id
});

const firstEntry = {id: AClockworkOrange.id, author: TheHobbit.author }
const secondEntry = {id: AClockworkOrange.id, title: 'Zack' }
const withNothingSorted = adapter.setAll(state, [TheHobbit]);
const withNothingUnsorted = unsortedAdaptor.setAll(state, [TheHobbit]);
const withOneSorted = adapter.setMany(withNothingSorted, [
{ ...AClockworkOrange, ...firstEntry, id: 'th' }, {...AClockworkOrange, ...secondEntry, id: 'th'}
])
const withOneUnsorted = unsortedAdaptor.setMany(withNothingUnsorted, [
{ ...AClockworkOrange, ...firstEntry, id: 'th' }, {...AClockworkOrange, ...secondEntry, id: 'th'}
])

expect(withOneSorted).toEqual(withOneUnsorted);
})

it('should let you set many entities in the state when passing in a dictionary', () => {
const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }
const withMany = adapter.setAll(state, [TheHobbit])
Expand Down
Loading