diff --git a/packages/toolkit/src/entities/sorted_state_adapter.ts b/packages/toolkit/src/entities/sorted_state_adapter.ts index 8f16ed2942..560d8a8896 100644 --- a/packages/toolkit/src/entities/sorted_state_adapter.ts +++ b/packages/toolkit/src/entities/sorted_state_adapter.ts @@ -1,4 +1,3 @@ -import { current, isDraft } from 'immer' import type { IdSelector, Comparer, @@ -71,7 +70,7 @@ export function createSortedStateAdapter( newEntities = ensureEntitiesArray(newEntities) const existingKeys = new Set( - existingIds ?? (current(state.ids) as Id[]), + existingIds ?? (getCurrent(state.ids) as Id[]), ) const models = newEntities.filter( diff --git a/packages/toolkit/src/entities/tests/sorted_state_adapter.test.ts b/packages/toolkit/src/entities/tests/sorted_state_adapter.test.ts index fb09089ece..93cff228f6 100644 --- a/packages/toolkit/src/entities/tests/sorted_state_adapter.test.ts +++ b/packages/toolkit/src/entities/tests/sorted_state_adapter.test.ts @@ -808,6 +808,31 @@ describe('Sorted State Adapter', () => { ) }) + it('should not throw an Immer `current` error when the adapter is called twice', () => { + const book1: BookModel = { id: 'a', title: 'First' } + const book2: BookModel = { id: 'b', title: 'Second' } + const initialState = adapter.getInitialState() + const booksSlice = createSlice({ + name: 'books', + initialState, + reducers: { + testCurrentBehavior(state, action: PayloadAction) { + // Will overwrite `state.ids` with a plain array + adapter.removeAll(state) + + // will call `splitAddedUpdatedEntities` and call `current(state.ids)` + adapter.addOne(state, book1) + adapter.addOne(state, book2) + }, + }, + }) + + booksSlice.reducer( + initialState, + booksSlice.actions.testCurrentBehavior(book1), + ) + }) + describe('can be used mutably when wrapped in createNextState', () => { test('removeAll', () => { const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])