Skip to content
This repository was archived by the owner on Feb 3, 2020. It is now read-only.

Commit 257a627

Browse files
committed
fix: support primitive state
1 parent d57224d commit 257a627

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

src/handle-action.test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,11 @@ test('supports default state', () => {
7373
expect(newState1).toEqual({ baz: 0 });
7474
expect(newState1).toBe(state);
7575
});
76+
77+
test('supports primitive state', () => {
78+
const ac1 = createAction<void>('toUpperCase');
79+
const state = 'foobarbaz';
80+
const re = handleAction<string>(ac1, s => s.toUpperCase(), state);
81+
const newState1 = re(state, ac1());
82+
expect(newState1).toBe('FOOBARBAZ');
83+
});

src/handle-action.ts

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
Draft,
44
createDraft,
55
finishDraft,
6+
isDraftable,
67
} from 'immer';
78
import {
89
// eslint-disable-next-line no-unused-vars
@@ -22,15 +23,19 @@ export default function handleAction<S, AC extends TsActionCreator<any> = any>(
2223
): Reducer<S, ReturnType<AC>> {
2324
return (state: S | undefined, action: ReturnType<AC>) => {
2425
if (action.type === ac.type && state) {
25-
const draft = createDraft(state);
26-
const reResult = re(draft, action);
27-
const finishedDraft = finishDraft(draft);
26+
if (isDraftable(state)) {
27+
const draft = createDraft(state);
28+
const reResult = re(draft, action);
29+
const finishedDraft = finishDraft(draft);
2830

29-
if (finishedDraft === state && reResult !== undefined) {
30-
return reResult;
31-
}
31+
if (finishedDraft === state && reResult !== undefined) {
32+
return reResult;
33+
}
3234

33-
return finishedDraft;
35+
return finishedDraft;
36+
}
37+
// Support primitive-returning reducers
38+
return re(state as Draft<S>, action);
3439
}
3540
return (state || s) as any;
3641
};

0 commit comments

Comments
 (0)