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

Commit

Permalink
fix: support primitive state
Browse files Browse the repository at this point in the history
  • Loading branch information
knpwrs committed Feb 10, 2019
1 parent d57224d commit 257a627
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
8 changes: 8 additions & 0 deletions src/handle-action.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,11 @@ test('supports default state', () => {
expect(newState1).toEqual({ baz: 0 });
expect(newState1).toBe(state);
});

test('supports primitive state', () => {
const ac1 = createAction<void>('toUpperCase');
const state = 'foobarbaz';
const re = handleAction<string>(ac1, s => s.toUpperCase(), state);
const newState1 = re(state, ac1());
expect(newState1).toBe('FOOBARBAZ');
});
19 changes: 12 additions & 7 deletions src/handle-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
Draft,
createDraft,
finishDraft,
isDraftable,
} from 'immer';
import {
// eslint-disable-next-line no-unused-vars
Expand All @@ -22,15 +23,19 @@ export default function handleAction<S, AC extends TsActionCreator<any> = any>(
): Reducer<S, ReturnType<AC>> {
return (state: S | undefined, action: ReturnType<AC>) => {
if (action.type === ac.type && state) {
const draft = createDraft(state);
const reResult = re(draft, action);
const finishedDraft = finishDraft(draft);
if (isDraftable(state)) {
const draft = createDraft(state);
const reResult = re(draft, action);
const finishedDraft = finishDraft(draft);

if (finishedDraft === state && reResult !== undefined) {
return reResult;
}
if (finishedDraft === state && reResult !== undefined) {
return reResult;
}

return finishedDraft;
return finishedDraft;
}
// Support primitive-returning reducers
return re(state as Draft<S>, action);
}
return (state || s) as any;
};
Expand Down

0 comments on commit 257a627

Please sign in to comment.