Skip to content

Commit

Permalink
feat(input-value): make useInputValue more compatible
Browse files Browse the repository at this point in the history
  • Loading branch information
SyMind committed Apr 22, 2021
1 parent 28197d1 commit 342bbfa
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
6 changes: 6 additions & 0 deletions packages/input-value/src/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,9 @@ test('change value via onChange', () => {
act(() => result.current.onChange({target: {value: newValue}}));
expect(result.current.value).toBe(newValue);
});

test('target not in change value', () => {
const {result} = renderHook(() => useInputValue());
act(() => result.current.onChange('foo'));
expect(result.current.value).toBe('foo');
});
13 changes: 7 additions & 6 deletions packages/input-value/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import {useState, useCallback} from 'react';

interface ChangeEvent {
target: {value: string};
}

export interface InputValueState {
value: string;
onChange(e: ChangeEvent): void;
onChange(e: any): void;
}

export function useInputValue(initialValue: string = ''): InputValueState {
const [value, setValue] = useState(initialValue);
const onChange = useCallback(
(e: ChangeEvent) => setValue(e.target.value),
(event: any) => {
const v = event && event.target && 'value' in event.target
? (event.target as HTMLInputElement).value
: event;
setValue(v);
},
[]
);
return {value, onChange};
Expand Down

0 comments on commit 342bbfa

Please sign in to comment.