Skip to content

Commit 106de54

Browse files
committed
Fix Immer current usage when calling addManyMutably more than once
1 parent ff65194 commit 106de54

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

packages/toolkit/src/entities/sorted_state_adapter.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export function createSortedStateAdapter<T, Id extends EntityId>(
7171
newEntities = ensureEntitiesArray(newEntities)
7272

7373
const existingKeys = new Set<Id>(
74-
existingIds ?? (current(state.ids) as Id[]),
74+
existingIds ?? (getCurrent(state.ids) as Id[]),
7575
)
7676

7777
const models = newEntities.filter(

packages/toolkit/src/entities/tests/sorted_state_adapter.test.ts

+25
Original file line numberDiff line numberDiff line change
@@ -808,6 +808,31 @@ describe('Sorted State Adapter', () => {
808808
)
809809
})
810810

811+
it('should not throw an Immer `current` error when the adapter is called twice', () => {
812+
const book1: BookModel = { id: 'a', title: 'First' }
813+
const book2: BookModel = { id: 'b', title: 'Second' }
814+
const initialState = adapter.getInitialState()
815+
const booksSlice = createSlice({
816+
name: 'books',
817+
initialState,
818+
reducers: {
819+
testCurrentBehavior(state, action: PayloadAction<BookModel>) {
820+
// Will overwrite `state.ids` with a plain array
821+
adapter.removeAll(state)
822+
823+
// will call `splitAddedUpdatedEntities` and call `current(state.ids)`
824+
adapter.addOne(state, book1)
825+
adapter.addOne(state, book2)
826+
},
827+
},
828+
})
829+
830+
booksSlice.reducer(
831+
initialState,
832+
booksSlice.actions.testCurrentBehavior(book1),
833+
)
834+
})
835+
811836
describe('can be used mutably when wrapped in createNextState', () => {
812837
test('removeAll', () => {
813838
const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])

0 commit comments

Comments
 (0)