Skip to content

Commit

Permalink
Fix Immer current usage when calling addManyMutably more than once
Browse files Browse the repository at this point in the history
  • Loading branch information
JacobShafer committed May 21, 2024
1 parent ff65194 commit 106de54
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/toolkit/src/entities/sorted_state_adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,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 106de54

Please sign in to comment.