Skip to content

Commit 09c36a2

Browse files
authored
Merge pull request #4420 from JacobShafer/fix/4411_fix_sorted_ids
Fix Immer current usage when calling addManyMutably more than once
2 parents dc0cb57 + b1b845a commit 09c36a2

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

packages/toolkit/src/entities/sorted_state_adapter.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { current, isDraft } from 'immer'
21
import type {
32
IdSelector,
43
Comparer,
@@ -71,7 +70,7 @@ export function createSortedStateAdapter<T, Id extends EntityId>(
7170
newEntities = ensureEntitiesArray(newEntities)
7271

7372
const existingKeys = new Set<Id>(
74-
existingIds ?? (current(state.ids) as Id[]),
73+
existingIds ?? (getCurrent(state.ids) as Id[]),
7574
)
7675

7776
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)