// Copyright 2019 @polkadot/extension-ui authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import React, { useState, useEffect } from 'react'; import styled from 'styled-components'; import { Result, Validator } from '../validators'; interface BasicProps { isError?: boolean; value?: string; onChange?: (value: string) => void; } type Props = T & { className?: string; validator: Validator; component: React.ComponentType; onValidatedChange: (value: string | null) => void; } function ValidatedInput ({ className, component: Input, onValidatedChange, validator, ...props }: Props): React.ReactElement> { const [value, setValue] = useState(''); const [wasMounted, setWasMounted] = useState(false); const [validationResult, setValidationResult] = useState>(Result.ok('')); useEffect(() => { if (!wasMounted) { setWasMounted(true); return; } (async (): Promise => { const result = await validator(value); setValidationResult(result); onValidatedChange(Result.isOk(result) ? value : null); })(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [value, validator, onValidatedChange]); return (
{Result.isError(validationResult) && {validationResult.error.errorDescription}}
); } const ErrorMessage = styled.span` display: block; margin-top: -10px; font-size: ${({ theme }): string => theme.labelFontSize}; line-height: ${({ theme }): string => theme.labelLineHeight}; color: ${({ theme }): string => theme.errorColor}; `; ErrorMessage.displayName = 'ErrorMessage'; export default ValidatedInput;