import React , { useRef , useCallback , useState } from 'react' ; import * as Yup from 'yup' ; import { FormHandles } from '@unform/core' ; import { FiLogIn , FiMail } from 'react-icons/fi' ; import { Form } from '@unform/web' ; import { Link } from 'react-router-dom' ; import { Container , Content , Background , AnimationContainer } from './styles' ; import logoImg from '../../assets/logo.svg' ; import Input from '../../components/Input' ; import Button from '../../components/Button' ; import getValidationErrors from '../../utils/getValidationErrors' ; import { useToast } from '../../hooks/toast' ; import api from '../../services/api' ; interface ForgotPasswordFormData { email : string ; } const ForgotPassword = ( ) => { const [ loading , setLoading ] = useState ( false ) ; const formRef = useRef < FormHandles > ( null ) ; const { addToast } = useToast ( ) ; const handleSubmit = useCallback ( async ( data ) => { try { setLoading ( true ) ; formRef . current ?. setErrors ( { } ) ; const schema = Yup . object ( ) . shape ( { email : Yup . string ( ) . required ( 'Email obrigatório' ) . email ( 'Digite um e-mail válido' ) , } ) ; await schema . validate ( data , { abortEarly : false , } ) ; await api . post ( '/password/forgot' , { email : data . email , } ) ; addToast ( { type : 'success' , title : 'E-mail de recuperação enviado' , description : 'Enviamos um e-mail para confirmar a recuperação de senha, cheque sua caixa de entrada!' , } ) ; } catch ( err ) { if ( err instanceof Yup . ValidationError ) { const errors = getValidationErrors ( err ) ; formRef . current ?. setErrors ( errors ) ; return ; } addToast ( { type : 'error' , title : 'Erro na recuperação de senha' , description : 'Ocorreu um erro ao tentar fazer a recuperação de senha, tente novamente.' , } ) ; } finally { setLoading ( false ) ; } } , [ addToast ] ) ; return ( < Container > < Content > < AnimationContainer > < img src = { logoImg } alt = "GoBarber" / > < Form ref = { formRef } onSubmit = { handleSubmit } > < h1 > Recuperar Senha < /h1> < Input name = "email" icon = { FiMail } placeholder = "E-mail" / > < Button loading = { loading } type = "submit" > Recuperar < /Button> < /Form> < Link to = "/" > < FiLogIn /> Voltar ao Login < /Link> < /AnimationContainer> < /Content> < Background / > < /Container>); } ; export default ForgotPassword ;