Skip to content

Commit

Permalink
Fix Immer current usage when the value may not be a draft
Browse files Browse the repository at this point in the history
  • Loading branch information
markerikson committed May 16, 2024
1 parent 87e2e59 commit 4cc7b1f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
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 @@ -5,6 +5,7 @@ import {
createSlice,
configureStore,
nanoid,
PayloadAction,
} from '@reduxjs/toolkit'
import type { BookModel } from './fixtures/book'
import {
Expand Down Expand Up @@ -783,6 +784,30 @@ describe('Sorted State Adapter', () => {
//expect(numSorts).toBeLessThan(25_000)
})

it('should not throw an Immer `current` error when `state.ids` is a plain array', () => {
const book1: BookModel = { id: 'a', title: 'First' }
const initialState = adapter.getInitialState()
const withItems = adapter.addMany(initialState, [book1])
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.upsertMany(state, [book1])
},
},
})

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
2 changes: 1 addition & 1 deletion packages/toolkit/src/entities/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export function splitAddedUpdatedEntities<T, Id extends EntityId>(
): [T[], Update<T, Id>[], Id[]] {
newEntities = ensureEntitiesArray(newEntities)

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

const added: T[] = []
Expand Down

0 comments on commit 4cc7b1f

Please sign in to comment.