Skip to content

[EnityAdapter] setMany creates duplicated IDs for entities with the same ID #5106

@demyanm

Description

@demyanm

Related to #5096 and #4890.

When using the sorted state adapter, calling setMany with multiple entities sharing the same id results in duplicated IDs in state.ids.
The unsorted adapter works correctly.

This leads to inconsistent behavior between adapters and potentially unstable selector outputs.

import { createEntityAdapter } from '@reduxjs/toolkit'

interface BookModel {
  id: string
  title: string
  author?: string
}

const adapter = createEntityAdapter<BookModel>({
  selectId: (book) => book.id,
  sortComparer: (a, b) => a.title.localeCompare(b.title),
})

const unsortedAdapter = createEntityAdapter<BookModel>({
  selectId: (book) => book.id,
})

const state = adapter.getInitialState()

const AClockworkOrange = { id: 'aco', title: 'A Clockwork Orange' }

const withSorted = adapter.setMany(state, [
  { ...AClockworkOrange, author: 'A' },
  { ...AClockworkOrange, title: 'Zack' },
])

const withUnsorted = unsortedAdapter.setMany(state, [
  { ...AClockworkOrange, author: 'A' },
  { ...AClockworkOrange, title: 'Zack' },
])

console.log(withSorted)   // => {ids: ['aco', 'aco'], entities: {aco: {id: 'aco', title: 'Zack'}}}
console.log(withUnsorted) // => {ids: ['aco'], entities: {aco: {id: 'aco', title: 'Zack'}}}

Expected behavior:

  • Both adapters should behave consistently.
  • For setMany, the last occurrence of an entity ID should be preserved.
  • The state.ids array should not contain duplicates.

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