ghost-portal/packages/react-hooks/src/useFormField.ts
2021-01-03 11:33:39 +01:00

28 lines
700 B
TypeScript

// Copyright 2017-2021 @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
];
}