Skip to content

Commit

Permalink
Merge pull request #4420 from JacobShafer/fix/4411_fix_sorted_ids
Browse files Browse the repository at this point in the history
Fix Immer current usage when calling addManyMutably more than once
  • Loading branch information
EskiMojo14 authored Jun 28, 2024
2 parents dc0cb57 + b1b845a commit 09c36a2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
3 changes: 1 addition & 2 deletions packages/toolkit/src/entities/sorted_state_adapter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { current, isDraft } from 'immer'
import type {
IdSelector,
Comparer,
Expand Down Expand Up @@ -71,7 +70,7 @@ export function createSortedStateAdapter<T, Id extends EntityId>(
newEntities = ensureEntitiesArray(newEntities)

const existingKeys = new Set<Id>(
existingIds ?? (current(state.ids) as Id[]),
existingIds ?? (getCurrent(state.ids) as Id[]),
)

const models = newEntities.filter(
Expand Down
25 changes: 25 additions & 0 deletions packages/toolkit/src/entities/tests/sorted_state_adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<BookModel>) {
// 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])
Expand Down

0 comments on commit 09c36a2

Please sign in to comment.