Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 37 38 39 40 41 42 43 44 45 46 47 | 2x 2x 15x 6x 6x 6x 15x 15x 7x 7x 6x 15x | import * as React from "react";
export interface UseValueOptions<T> {
initialValue?: T | (() => T);
valuePropName?: string;
defaultValuePropName?: string;
trigger?: string;
}
export default function useValue<T>(
props: { [key: string]: any },
{
initialValue,
valuePropName = "value",
defaultValuePropName: optionDefaultValuePropName,
trigger = "onChange",
}: UseValueOptions<T> = {},
): [T, (value: T, ...args: any[]) => void] {
const defaultValue = React.useMemo<T>(() => {
const defaultValuePropName =
optionDefaultValuePropName ||
`default${valuePropName.replace(/^(.)/, c => c.toUpperCase())}`;
/* eslint-disable no-nested-ternary */
return props[defaultValuePropName] !== undefined
? props[defaultValuePropName]
: typeof initialValue === "function"
? (initialValue as any)()
: initialValue;
}, []);
const [value, setValue] = React.useState<T>(defaultValue);
const handleValueChange = React.useCallback(
(nextValue, ...args) => {
setValue(nextValue);
if (typeof props[trigger] === "function") {
props[trigger](nextValue, ...args);
}
},
[props[trigger]],
);
return [
props[valuePropName] !== undefined ? props[valuePropName] : value,
handleValueChange,
];
}
|