* Add eslint configuration * Patch eslint plugin for sorting imports * Apply eslint rules for imports
28 lines
700 B
TypeScript
28 lines
700 B
TypeScript
// Copyright 2017-2020 @polkadot/react-hooks authors & contributors
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
import { useMemo, useState } from 'react';
|
|
|
|
import { isUndefined } from '@polkadot/util';
|
|
|
|
export type FormField<T> = [
|
|
T | null,
|
|
boolean,
|
|
(_?: T | null) => void
|
|
];
|
|
|
|
export function useFormField<T> (defaultValue: T | null, validate: (_: T) => boolean = (): boolean => true): FormField<T> {
|
|
const [value, setValue] = useState<T | null>(defaultValue);
|
|
const isValid = useMemo(
|
|
(): boolean => !!value && validate(value),
|
|
[validate, value]
|
|
);
|
|
const setter = (value?: T | null) => !isUndefined(value) && setValue(value);
|
|
|
|
return [
|
|
value,
|
|
isValid,
|
|
setter
|
|
];
|
|
}
|