Skip to content

[EntityAdapter] sorted_state_adapter: addMany mis-handles duplicate IDs (should preserve first occurrence) #5096

@demyanm

Description

@demyanm

This issue is related to PR #4890 (which fixed upsertMany behavior for multiple updates to the same new entity).
In a similar vein, there is now a bug in sorted_state_adapter affecting the addMany method when duplicate ids are passed.

With the unsorted adapter, addMany([{ id: 'a', value: 1 }, { id: 'a', value: 2 }]) preserves the first entity for id = 'a'.
But with the sorted adapter, the last entity is retained instead, which is inconsistent with unsorted adapter behavior and likely unexpected by users.

import { createEntityAdapter } from '@reduxjs/toolkit';

interface Item {
  id: string;
  value: number;
}

const updates = [
  { id: 'a', value: 1 },
  { id: 'a', value: 2 },
];

// Unsorted adapter works as expected
const unsorted = createEntityAdapter<Item>();
let state = unsorted.getInitialState();

state = unsorted.addMany(state, updates);
console.log(state.entities['a']); // { id: 'a', value: 1 } ====> correct

// Sorted adapter exhibits the bug
const sorted = createEntityAdapter<Item>({
  sortComparer: (a, b) => a.value - b.value,
});
state = sorted.getInitialState();
state = sorted.addMany(state, updates);
console.log(state.entities['a']); // { id: 'a', value: 2 } ====> incorrect

Redux Toolkit version: 2.9.0

Expected behavior:
In sorted_state_adapter, addMany should preserve the first occurrence for any duplicate id, matching how unsorted_state_adapter behaves.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions