forked from coldemo/gallery.code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseFormBinding.ts
More file actions
36 lines (28 loc) · 846 Bytes
/
useFormBinding.ts
File metadata and controls
36 lines (28 loc) · 846 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { useCallback, useMemo, useState } from 'react';
type ParseValue<T> = (...args: any[]) => T;
// @todo uncontrolled / defaultValue
export let useFormBinding = <T>(_initial: T, _parseValue?: ParseValue<T>) => {
let defaultParseValue: ParseValue<T> = useCallback(e => {
let r = e;
if (e && e.target && 'value' in e.target) {
r = e.target.value;
}
return r;
}, []);
let [initial, parseValue] = useMemo(() => {
return [_initial, _parseValue || defaultParseValue];
}, [_initial, _parseValue, defaultParseValue]);
let [value, setValue] = useState<T>(initial);
let handleChange = useCallback(
(e, ...rest) => {
let r = parseValue(e, ...rest);
setValue(r);
},
[parseValue]
);
let controlled = {
value,
onChange: handleChange,
};
return { value, controlled };
};