Skip to content

Commit 1602a36

Browse files
committed
Simplify immutable entity operations by wrapping with Immer
1 parent 8bfdaf7 commit 1602a36

File tree

1 file changed

+10
-17
lines changed

1 file changed

+10
-17
lines changed

src/entities/state_adapter.ts

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import createNextState, { Draft } from 'immer'
12
import { EntityState } from './models'
23

34
export enum DidMutate {
@@ -13,24 +14,16 @@ export function createStateOperator<V, R>(
1314
mutator: (arg: any, state: any) => DidMutate
1415
): any {
1516
return function operation<S extends EntityState<V>>(arg: R, state: any): S {
16-
const clonedEntityState: EntityState<V> = {
17-
ids: [...state.ids],
18-
entities: { ...state.entities }
19-
}
17+
// @ts-ignore createNextState() produces an Immutable<Draft<S>> rather
18+
// than an Immutable<S>, and TypeScript cannot find out how to reconcile
19+
// these two types.
20+
return createNextState(state, (draft: Draft<EntityState<V>>) => {
21+
const { ids: originalIds } = draft
22+
const didMutate = mutator(arg, draft)
2023

21-
const didMutate = mutator(arg, clonedEntityState)
22-
23-
if (didMutate === DidMutate.Both) {
24-
return Object.assign({}, state, clonedEntityState)
25-
}
26-
27-
if (didMutate === DidMutate.EntitiesOnly) {
28-
return {
29-
...state,
30-
entities: clonedEntityState.entities
24+
if (didMutate === DidMutate.EntitiesOnly) {
25+
draft.ids = originalIds
3126
}
32-
}
33-
34-
return state
27+
})
3528
}
3629
}

0 commit comments

Comments
 (0)