ghost-portal/packages/react-hooks/src/useFormField.ts
Jaco Greeff 64299ebd29
Dev bump (#4012)
* Bump API/Common (esnext exports)

* Bump deps

* Adjust

* Bumps

* Bumps

* repository

* Update dev

* Remove Rococo (for the time being)

* script extension
2020-11-11 15:28:52 +01:00

27 lines
699 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
];
}