Skip to content

Commit

Permalink
Merge pull request #160 from nlundquist/add-initializer-to-use-reducer
Browse files Browse the repository at this point in the history
add initializer argument to useReducer
  • Loading branch information
matthewp authored Dec 16, 2019
2 parents b4c8eb9 + 2bab26d commit 42f9c27
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
6 changes: 3 additions & 3 deletions src/use-reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import { State } from './state';

type Reducer<S, A> = (state: S, action: A) => S;

const useReducer = hook(class<S, A> extends Hook {
const useReducer = hook(class<S, I, A> extends Hook {
reducer!: Reducer<S, A>;
currentState: S;

constructor(id: number, state: State, _: Reducer<S, A>, initialState: S) {
constructor(id: number, state: State, _: Reducer<S, A>, initialState: I, init?: (_:I) => S) {
super(id, state);
this.dispatch = this.dispatch.bind(this);
this.currentState = initialState;
this.currentState = init !== undefined ? init(initialState) : <S><any>initialState;
}

update(reducer: Reducer<S, A>): readonly [S, (action: A) => void] {
Expand Down
4 changes: 3 additions & 1 deletion test/types-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,12 @@ const [state2, setState2] = useState(undefined); setState2 + 1;
// useReducer tests
// positive tests, should all pass
useReducer(() => {}, undefined);
useReducer((state: number) => state, 1)
useReducer((state: number) => state, 1);
useReducer((state: string) => state, 1, (value: number) => value.toString());
// negactive tests, should all fail
useReducer();
const useReducerTest1 = useReducer(() => {});
useReducer((state: string) => state, 1, (value: Date) => value.toString());
useReducerTest1 + 1;

// useMemo tests
Expand Down

0 comments on commit 42f9c27

Please sign in to comment.