react-hook-form#useWatch JavaScript Examples

The following examples show how to use react-hook-form#useWatch. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: new.js    From paras-landing with GNU General Public License v3.0 6 votes vote down vote up
RoyaltyWatch = ({ control, append }) => {
	const { localeLn } = useIntl()

	const royalties = useWatch({
		control,
		name: 'royalties',
		defaultValue: [],
	})

	return (
		<div className="flex items-center justify-between mb-1">
			<label className="block text-sm">
				<span className="pr-1">{localeLn('Royalty')}</span>
				{calcRoyalties(royalties) > 90 ? (
					<span className="text-red-500 text-semibold">{calcRoyalties(royalties)}%</span>
				) : (
					<span className="text-semibold">{calcRoyalties(royalties)}%</span>
				)}
			</label>
			<button
				className="flex items-center"
				disabled={royalties.length >= 10 || calcRoyalties(royalties) >= 90}
				onClick={() => append({ accountId: '', value: '' })}
			>
				<span className="text-sm pr-2">Add</span>
				<IconX style={{ transform: 'rotate(45deg)' }} className="cursor-pointer" size={20} />
			</button>
		</div>
	)
}
Example #2
Source File: ProposalCreationForm.jsx    From pooltogether-governance-ui with MIT License 6 votes vote down vote up
DescriptionCard = (props) => {
  const { t } = useTranslation()
  const { register, control } = useFormContext()
  const name = 'description'
  const text = useWatch({ control, name, defaultValue: '' })

  return (
    <Card className='mb-6'>
      <h4 className='mb-2'>{t('description')}</h4>
      <p className='mb-8'>{t('theDescriptionShouldPresentInFullDescription')}</p>
      <MarkdownInputArea name={name} text={text} register={register} />
    </Card>
  )
}
Example #3
Source File: index.js    From plataforma-sabia with MIT License 6 votes vote down vote up
PasswordStrength = ({ form, inputToWatch, mobileBreakpoint }) => {
	const inputValue = useWatch({
		control: form.control,
		name: inputToWatch,
	});
	const strength = checkPasswordStrength(inputValue);

	return (
		<S.Wrapper mobileBreakpoint={mobileBreakpoint}>
			<S.Container>
				<S.Title>Sua senha deve conter:</S.Title>
				<S.StrengthList>
					{strengthList.map((item) => (
						<S.StrengthItem key={item.key} success={strength[item.key]}>
							{item.text}
						</S.StrengthItem>
					))}
				</S.StrengthList>
			</S.Container>
		</S.Wrapper>
	);
}
Example #4
Source File: Action.jsx    From pooltogether-governance-ui with MIT License 5 votes vote down vote up
CustomContractInputMainnet = (props) => {
  const { contract, setContract, contractPath } = props

  const { t } = useTranslation()
  const [showAbiInput, setShowAbiInput] = useState(false)
  const addressFormName = `${contractPath}.address`
  const { register, control, errors } = useFormContext()

  const address = useWatch({ control, name: addressFormName })

  const { data: etherscanAbiUseQueryResponse, isFetching: etherscanAbiIsFetching } =
    useEtherscanAbi(address, showAbiInput)

  useEffect(() => {
    if (showAbiInput) return

    // If there was no response, clear the abi in the form
    if (!etherscanAbiUseQueryResponse) {
      if (contract.abi) {
        setContract({
          ...contract,
          abi: null
        })
      }
      return
    }

    handleEtherscanAbiUseQueryResponse(etherscanAbiUseQueryResponse, setContract, contract)
  }, [etherscanAbiUseQueryResponse, showAbiInput])

  const etherscanAbiStatus = etherscanAbiUseQueryResponse?.data?.status
  const errorMessage = getErrorMessage(errors?.[addressFormName]?.message, etherscanAbiStatus)

  return (
    <>
      <SimpleInput
        className='mt-2'
        label={t('contractAddress')}
        errorMessage={errorMessage}
        name={addressFormName}
        register={register}
        required
        validate={(address) => isValidAddress(address) || t('invalidContractAddress')}
        placeholder='0x1f9840a85...'
        loading={etherscanAbiIsFetching}
      />
      {showAbiInput && <CustomAbiInput contract={contract} setContract={setContract} />}

      <div className='flex flex-col xs:flex-row xs:w-3/4 xs:ml-auto'>
        <button
          type='button'
          onClick={(e) => {
            e.preventDefault()
            setShowAbiInput(!showAbiInput)
          }}
          className='xs:ml-auto mt-2 w-fit-content text-xxs text-inverse hover:opacity-50 trans'
        >
          {showAbiInput ? t('hideAbiInput') : t('haveTheAbiManuallyInput')}
        </button>
      </div>
    </>
  )
}
Example #5
Source File: index.js    From plataforma-sabia with MIT License 4 votes vote down vote up
StepThree = ({ activeStep, setNextStep, userData, updateUserData }) => {
	const verificationCodeRef = useRef();
	const [isFetching, setIsFetching] = useState(false);
	const form = useForm({
		defaultValues: { email: '', verificationCode: Array(6).fill('') },
		reValidateMode: 'onSubmit',
	});
	const verificationCode = useWatch({
		control: form.control,
		name: 'verificationCode',
	});
	const { t } = useTranslation(['error']);
	const router = useRouter();
	const shouldShowEmailField = router.pathname === internalPages.confirm_account;

	useEffect(() => {
		if (shouldShowEmailField) {
			form.setFocus('email');
			return;
		}

		if (verificationCodeRef.current) {
			verificationCodeRef.current.focus();
		}

		// We only want this to run when component is mounted
		// react-hook-form funcs is already memoized
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	const handleSubmit = async (values) => {
		setIsFetching(true);

		const response = await accountConfirmation(
			values.verificationCode.join(''),
			userData.email || values.email,
		);

		if (response?.error) {
			const errorMessage =
				typeof response.error.message === 'string'
					? response.error.message
					: response.error.message[0].message;

			toast.error(
				errorMessage ||
					'Ocorreu um erro para validar seu registro. Tente novamente em alguns instantes...',
			);
			setIsFetching(false);
			form.reset();

			if (shouldShowEmailField) {
				form.setFocus('email');
			} else {
				verificationCodeRef.current.focus();
			}
			return;
		}

		updateUserData(response);
		setNextStep();
	};

	useEffect(() => {
		const isAllFilled = verificationCode.every((code) => code.length > 0);

		if (isAllFilled && !shouldShowEmailField) {
			form.handleSubmit(handleSubmit)();
		}
		// react-hook-form funcs is already memoized
		// Everytime `verificationCode` changes, `shouldShowEmailField` also change, so we don't need it here
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [verificationCode]);

	const handleResendEmailConfirmation = async () => {
		const { email } = form.getValues();

		if (!userData.email && !email) {
			form.setError('email', { message: t('error:requiredField') });
			return;
		}

		form.clearErrors();
		setIsFetching(true);
		const response = await emailConfirmation(userData.email || email);

		if (response?.error) {
			toast.error(
				response.error.message[0].message ||
					'Ocorreu um erro para efetuar seu registro. Recarregue a página e tente novamente...',
			);
			setIsFetching(false);
			return;
		}

		if (response.success) {
			toast.success(
				'Caso o e-mail informado corresponda a um usuário cadastrado, enviaremos o código de verificação para você',
			);

			if (!userData.email && !!email) updateUserData({ email });
		}

		setIsFetching(false);
	};

	return (
		<Form onSubmit={form.handleSubmit(handleSubmit)}>
			<StepTitle>{activeStep.title}</StepTitle>
			<StepSubtitle>{activeStep.subtitle}</StepSubtitle>
			<StepInfo>
				{shouldShowEmailField ? (
					<>
						Digite abaixo seu e-mail e o código de <strong>6 dígitos</strong> para
						validar sua conta
					</>
				) : (
					<>
						Digite abaixo o código de <strong>6 dígitos</strong> que enviamos para o seu
						e-mail.
					</>
				)}
			</StepInfo>
			<S.InputsWrapper>
				{shouldShowEmailField && (
					<InputField
						name="email"
						label="E-mail"
						placeholder="Digite seu e-mail"
						variant="lightRounded"
						form={form}
						validation={{ required: true }}
					/>
				)}
				<S.VerificationCodeWrapper>
					<Controller
						name="verificationCode"
						control={form.control}
						rules={{
							validate: {
								allFieldsFilled: (value) => {
									return (
										value.every((_val) => _val.length) ||
										t('error:requiredField')
									);
								},
							},
						}}
						render={({ field, fieldState }) => (
							<VerificationCodeField
								ref={verificationCodeRef}
								value={field.value}
								onChange={field.onChange}
								label={shouldShowEmailField ? 'Código de verificação' : ''}
								error={fieldState.error}
								required
							/>
						)}
					/>
					<S.ResendEmailLink>
						<RectangularButton
							disabled={isFetching}
							colorVariant="blue"
							onClick={handleResendEmailConfirmation}
						>
							Enviar novamente
						</RectangularButton>
					</S.ResendEmailLink>
				</S.VerificationCodeWrapper>
			</S.InputsWrapper>

			<Actions>
				<RectangularButton
					disabled={isFetching}
					variant="round"
					colorVariant="green"
					type="submit"
				>
					Validar
					<FiArrowRight fontSize="2rem" />
				</RectangularButton>
			</Actions>
		</Form>
	);
}
Example #6
Source File: StepThree.js    From plataforma-sabia with MIT License 4 votes vote down vote up
StepThree = ({ activeStep, setNextStep, updateUserData, userData }) => {
	const [isSubmitting, setIsSubmitting] = useState(false);
	const [error, setError] = useState('');
	const form = useForm({
		defaultValues: { password: '', confirmPassword: '' },
	});
	const { resetPassword } = useAuth();
	const passwordValue = useWatch({
		control: form.control,
		name: 'password',
	});
	const theme = useTheme();

	const handleSubmit = async ({ password }) => {
		setIsSubmitting(true);
		setError('');

		const response = await resetPassword({
			email: userData.email,
			token: userData.token,
			password,
		});

		if (response.error) {
			setError(response.error.message?.[0]?.message || response.error.message);
			setIsSubmitting(false);
			return;
		}

		updateUserData({ password });
		setNextStep();
	};

	return (
		<S.Wrapper>
			<S.Form onSubmit={form.handleSubmit(handleSubmit)}>
				<S.StepTitle>{activeStep.title}</S.StepTitle>
				<S.StepSubtitle smallFontSize>{activeStep.subtitle}</S.StepSubtitle>

				{!!error && <Error message={error} />}

				<S.InputsWrapper>
					<S.PasswordWrapper>
						<InputField
							form={form}
							validation={{
								required: true,
								validate: {
									passwordStrength: (value) => {
										const strength = checkPasswordStrength(value);

										const isValid = Object.values(strength).every(
											(item) => !!item,
										);

										return isValid || '';
									},
								},
							}}
							name="password"
							label="Informe a sua nova senha"
							placeholder="Digite sua nova senha"
							variant="lightRounded"
							type="password"
						/>
						<PasswordStrength
							form={form}
							inputToWatch="password"
							mobileBreakpoint={theme.screens.large}
						/>
					</S.PasswordWrapper>
					<InputField
						form={form}
						validation={{
							required: true,
							validate: {
								passwordMatch: (value) =>
									passwordValue === value || 'As senhas não são iguais',
							},
						}}
						name="confirmPassword"
						label="Confirme a sua nova senha"
						placeholder="Repita a sua senha"
						variant="lightRounded"
						type="password"
					/>
				</S.InputsWrapper>

				<S.Actions>
					<RectangularButton
						colorVariant="green"
						variant="round"
						type="submit"
						disabled={isSubmitting}
						fullWidth
					>
						{isSubmitting ? 'Aguarde...' : 'Confirmar alteração'}
					</RectangularButton>
				</S.Actions>
			</S.Form>
		</S.Wrapper>
	);
}
Example #7
Source File: StepTwo.js    From plataforma-sabia with MIT License 4 votes vote down vote up
StepTwo = ({ activeStep, setNextStep, setPrevStep, userData, updateUserData }) => {
	const [isSubmitting, setIsSubmitting] = useState(false);
	const [error, setError] = useState('');
	const verificationCodeRef = useRef();
	const form = useForm({
		defaultValues: { verificationCode: Array(6).fill('') },
		reValidateMode: 'onSubmit',
	});
	const verificationCode = useWatch({
		control: form.control,
		name: 'verificationCode',
	});
	const { requestPasswordReset } = useAuth();
	const { t } = useTranslation();

	useEffect(() => {
		if (verificationCodeRef.current) {
			verificationCodeRef.current.focus();
		}

		// We only want this to run when component is mounted
		// react-hook-form funcs is already memoized
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	const handleSubmit = async () => {
		setIsSubmitting(true);
		setError('');
		const token = verificationCode.join('');

		const response = await checkVerificationCode({
			email: userData.email,
			token,
			tokenType: 'reset-password',
		});

		if (response.error) {
			setError(response.error.message?.[0]?.message || response.error.message);
			setIsSubmitting(false);
			form.reset();
			verificationCodeRef.current.focus();
			return;
		}

		updateUserData({ token });
		setNextStep();
	};

	useEffect(() => {
		const isAllFilled = verificationCode.every((code) => code.length > 0);

		if (isAllFilled) {
			form.handleSubmit(handleSubmit)();
		}
		// react-hook-form funcs is already memoized
		// Everytime `verificationCode` changes, `shouldShowEmailField` also change, so we don't need it here
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [verificationCode]);

	const handleResendCodeValidation = async () => {
		form.clearErrors();
		setIsSubmitting(true);
		const response = await requestPasswordReset({ email: userData.email });

		if (response?.error) {
			toast.error(
				response.error.message[0].message ||
					'Ocorreu um erro para efetuar seu registro. Recarregue a página e tente novamente...',
			);
			setIsSubmitting(false);
			return;
		}

		if (response.success) {
			toast.success('Enviamos um novo código para o seu e-mail!');
			verificationCodeRef.current.focus();
		}

		setIsSubmitting(false);
	};

	return (
		<S.Wrapper>
			<S.Form onSubmit={form.handleSubmit(handleSubmit)}>
				<S.StepTitle>{activeStep.title}</S.StepTitle>
				<S.StepSubtitle smallFontSize>{activeStep.subtitle}</S.StepSubtitle>

				{!!error && <Error message={error} />}

				<S.InputsWrapper>
					<S.VerificationCodeWrapper>
						<Controller
							name="verificationCode"
							control={form.control}
							rules={{
								validate: {
									allFieldsFilled: (value) => {
										return (
											value.every((_val) => _val.length) ||
											t('error:requiredField')
										);
									},
								},
							}}
							render={({ field, fieldState }) => (
								<VerificationCodeField
									ref={verificationCodeRef}
									value={field.value}
									onChange={field.onChange}
									error={fieldState.error}
									required
								/>
							)}
						/>
						<S.ResendEmailLink>
							<RectangularButton
								disabled={isSubmitting}
								colorVariant="blue"
								onClick={handleResendCodeValidation}
							>
								Enviar novamente
							</RectangularButton>
						</S.ResendEmailLink>
					</S.VerificationCodeWrapper>
				</S.InputsWrapper>

				<S.Actions>
					<RectangularButton colorVariant="blue" onClick={setPrevStep} fullWidth>
						<FiCornerUpLeft fontSize="2rem" />
						<span>Voltar para a tela anterior</span>
					</RectangularButton>
				</S.Actions>
			</S.Form>
		</S.Wrapper>
	);
}